1

我对 rails 和 webpacker 非常陌生,无法弄清楚这里发生了什么。当我从浏览器的地址栏中“完全加载”我的应用程序时,工具提示和弹出框没有被实例化,并且我收到如下错误:

  • application.js:32 Uncaught TypeError: $(...).tooltip 不是函数

但是,当我从应用程序中加载页面时(单击导航栏中的链接),工具提示和弹出框按预期工作。另外,如果我去 chrome 控制台并手动实例化它们,工具提示和弹出框开始工作:

$('[data-bs-toggle="tooltip"]').tooltip();

以下是我认为相关的一些配置:

包/application.js

// This file is automatically compiled by Webpack, along with any other files
// present in this directory. You're encouraged to place your actual application logic in
// a relevant structure within app/javascript and only use these pack files to reference
// that code so it'll be compiled.

import Rails from "@rails/ujs"
import Turbo from "@hotwired/turbo"
import "@hotwired/turbo-rails"
import * as ActiveStorage from "@rails/activestorage"
import "channels"



import 'bootstrap'
import '../stylesheets/application'

import "controllers"

Rails.start()

ActiveStorage.start()


document.addEventListener("turbo:load", () => {
    console.log("turbo!");


    $('[data-bs-toggle="tooltip"]').tooltip();
    $('[data-bs-toggle="popover"]').popover();

});

webpack/environment.js

environment.plugins.append(
'Provide',
new webpack.ProvidePlugin({
$: 'jquery',
  jQuery: 'jquery',
  Popper: ['popper.js', 'default']
  })
);
environment.config.merge(customConfig);
module.exports = environment;

webpack/custom.js:

    resolve: {
      alias: {
        jquery: 'jquery/src/jquery'
      }
    }
  };

布局/application.html.erb:

    <%= javascript_pack_tag 'application', 'data-turbo-track': 'reload' %>
    <%= stylesheet_link_tag 'application', media: 'all', 'data-turbo-track': 'reload' %>
    <%= stylesheet_pack_tag 'application', media: 'all', 'data-turbo-track': 'reload' %>

包.json:

{
  "name": "deploy-dashboard",
  "private": true,
  "dependencies": {
    "@hotwired/turbo": "^7.0.0-beta.5",
    "@hotwired/turbo-rails": "^7.0.0-beta.5",
    "@popperjs/core": "^2.9.2",
    "@rails/actioncable": "^6.0.0",
    "@rails/activestorage": "^6.0.0",
    "@rails/ujs": "^6.0.0",
    "@rails/webpacker": "5.2.1",
    "bootstrap": "^5.0.0",
    "jquery": "^3.6.0",
    "popper.js": "^1.16.1",
    "stimulus": "^2.0.0"
  },
  "version": "0.1.0",
  "devDependencies": {
    "webpack-dev-server": "^3.11.2"
  }
}
4

1 回答 1

1

尝试

document.addEventListener("turbo:load", function() {
  $(function () {
    $('[data-toggle="tooltip"]').tooltip();
    $('[data-toggle="popover"]').popover();
  })
})
于 2021-05-31T12:08:31.973 回答