无法理解为什么我无法使任何jQuery插件功能(引导程序、日期选择器等(正常工作:
$(...).datepicker()
或$(...).modal()
用... is not a function in Rails 6
响应
几个注意事项:
- $和jQuery正在控制台中响应
- jQuery包含在其他脚本之前
- jQuery包含一次
application.js:
require("@rails/ujs").start()
require("turbolinks").start()
require("@rails/activestorage").start()
require("channels")
require("jquery")
require("parsleyjs")
require("bootstrap-datepicker")
import '../stylesheets/application'
import './bootstrap_custom.js'
import './ru.js'
package.json:
{
"name": "joy",
"private": true,
"dependencies": {
"@rails/actioncable": "^6.0.0-alpha",
"@rails/activestorage": "^6.0.0-alpha",
"@rails/ujs": "^6.0.0-alpha",
"@rails/webpacker": "^4.0.7",
"bootstrap": "4.3.1",
"bootstrap-datepicker": "^1.9.0",
"jquery": "^3.4.1",
"parsleyjs": "^2.9.1",
"popper.js": "^1.16.0",
"turbolinks": "^5.2.0"
},
"version": "0.1.0",
"devDependencies": {
"webpack-dev-server": "^3.8.2"
}
}
env.js:
const { environment } = require('@rails/webpacker')
const webpack = require('webpack')
environment.plugins.append(
'Provide',
new webpack.ProvidePlugin({
$: 'jquery/src/jquery',
jQuery: 'jquery/src/jquery',
Popper: ['popper.js', 'default'],
Parsley: 'parsleyjs/src/parsley.js',
datepicker: 'bootstrap-datepicker/js/bootstrap-datepicker.js'
})
)
module.exports = environment
顺便说一句,如果我用data-toggle
调用bootstrap的模态,它就会成功打开。
尝试向application.js添加以下代码:
import jquery from 'jquery';
window.$ = window.jquery = jquery;
并尝试更改application.js中的jquery,如下所示。
const { environment } = require('@rails/webpacker')
const webpack = require('webpack')
environment.plugins.prepend('Provide', new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
'window.jQuery': 'jquery',
Popper: ['popper.js', 'default'],
moment: 'moment/moment',
datepicker: 'bootstrap-datepicker/js/bootstrap-datepicker.js'
}))
module.exports = environment