首页 > 解决方案 > Rails 6 + webpack 错误:未捕获的 TypeError:$(...).popover 不是函数

问题描述

我正在 Rails 6 中开始一个新项目,这将是我第一次使用 Webpack,我在使用 popover tooltip dropdown遇到问题。

application.js:37 Uncaught TypeError: $(...).dropdown 不是函数

环境.js

const { environment } = require('@rails/webpacker')

const webpack = require('webpack')
environment.plugins.append('Provide',
    new webpack.ProvidePlugin({
        $: 'jquery/src/jquery',
        jQuery: 'jquery/src/jquery',
        jquery: 'jquery',
        'window.jQuery': 'jquery',
        Popper: ['popper.js', 'default'],
        Rails: ['@rails/ujs']
    })
)

module.exports = environment

应用程序.js

import 'core-js/stable'
import 'regenerator-runtime/runtime'

require("@rails/ujs").start()
require("turbolinks").start()
require("channels")

import 'bootstrap'
import './menu-left.cleanui-custom'
import './menu-right.cleanui-custom'
// Uncomment to copy all static images under ../images to the output folder and reference
// them with the image_pack_tag helper in views (e.g <%= image_pack_tag 'rails.png' %>)
// or the `imagePath` JavaScript helper below.
//
// const images = require.context('../images', true)
// const imagePath = (name) => images(name, true)

import '../stylesheets/application'


document.addEventListener("turbolinks:load", () => {
    $('[data-toggle=popover-hover]').popover({
        trigger: 'hover',
        animation: false
    });
    $("[data-toggle=tooltip]").tooltip({
        trigger: 'hover',
        animation: false
    });
});

$('.dropdown-toggle').dropdown();

错误可能来自哪里?事实是我仍然对 webpack 很迷茫。

标签: ruby-on-railswebpackpopoverruby-on-rails-6

解决方案


这对我有用:

config/webpack/environment.js

const { environment } = require('@rails/webpacker')

const webpack = require('webpack')
environment.plugins.prepend('Provide',
  new webpack.ProvidePlugin({
    $: 'jquery/src/jquery',
    jQuery: 'jquery/src/jquery',
    Popper: ['popper.js', 'default']
  })
)
environment.config.merge(
  module.exports = {
    resolve: {
      alias: {
        jquery: 'jquery/src/jquery',
      }
    }
  }
)

module.exports = environment

app/javascript/packs/application.js

require("@rails/ujs").start()
require("turbolinks").start()
import "jquery"
import 'bootstrap'

document.addEventListener("turbolinks:load", function() {
  $(function () {
      $('[data-toggle="tooltip"]').tooltip()
      $('[data-toggle="popover"]').popover()
  })
})

推荐阅读