问题描述
开始一个新的Rails 6.0.3项目,并添加jQuery和Bootstrap。 jQuery可以正常工作,并且Bootstrap CSS似乎可以正确呈现,但是每当我尝试在浏览器JavaScript控制台中运行$.fn.tooltip.Constructor.VERSION
时,都会出现错误Uncaught TypeError: Cannot read property 'tooltip' of undefined
。此外,尝试添加插件(例如,引导程序选择,引导程序标签输入等)均失败。我不确定是否相关,但是添加真棒字体时我也遇到了同样的麻烦,CSS可以工作,但是Javascript不能。以下是可能相关的配置:
// package.json
{
"name": "myproject","private": true,"dependencies": {
"@rails/actioncable": "^6.0.0","@rails/activestorage": "^6.0.0","@rails/ujs": "^6.0.0","@rails/webpacker": "5.2.1","bootstrap": "^4.5.2","channels": "^0.0.4","jquery": "^3.5.1","popper.js": "^1.16.1","turbolinks": "^5.2.0"
},"version": "0.1.0","devDependencies": {
"axios": "^0.20.0","cypress": "^5.1.0","webpack-dev-server": "^3.11.0"
}
}
// 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']
})
)
module.exports = environment
// config/webpack/development.js
process.env.NODE_ENV = process.env.NODE_ENV || 'development'
const environment = require('./environment')
module.exports = environment.toWebpackConfig()
// app/javascript/packs/application.js
require("jquery")
require("@rails/ujs").start()
require("turbolinks").start()
require("@rails/activestorage").start()
require("channels")
require("bootstrap")
// app/views/layouts/application.html.erb
<!doctype html>
<html lang="en">
<head>
<Meta charset="utf-8">
<Meta name="viewport" content="width=device-width,initial-scale=1,shrink-to-fit=no">
<%= csrf_Meta_tags %>
<%= csp_Meta_tag %>
<%= stylesheet_link_tag 'application',media: 'all','data-turbolinks-track': 'reload' %>
<%= javascript_pack_tag 'application','data-turbolinks-track': 'reload' %>
<title>My Project</title>
</head>
<body>
<%= yield %>
</body>
</html>
解决方法
通过以下添加使其工作...
// config/webpack/custom.js
module.exports = {
resolve: {
alias: {
jquery: 'jquery/src/jquery'
}
}
};
...并进行更改:
// config/webpack/environment.js
const { environment } = require('@rails/webpacker')
const customConfig = require('./custom')
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(customConfig)
module.exports = environment
// config/webpack/environment.js
require("jquery")
require("@rails/ujs").start()
require("turbolinks").start()
require("@rails/activestorage").start()
require("channels")
require("bootstrap")
import $ from "jquery"
document.addEventListener("turbolinks:load",() => {
$('[data-toggle="tooltip"]').tooltip()
$('[data-toggle="popover"]').popover()
})
有助于解决问题的相关问题:$(...).tooltip is not a function rails 6 webpack