我已经设置了一个新的Rails 6应用程序以与tailwindcss一起使用,这是我第一次体验到正确使用webpack的经历。我正在尝试使用jquery,并希望确保脚本中对$或jquery的任何引用均得到正确支持
我已经followed the instructions安装了jquery-ui软件包,这需要我创建一个webpack.config.js文件,但是除非我也在application.js中定义了jquery标签,否则它似乎不起作用。
虽然这可以暂时解决我的问题,但我想确保正确设置webpack.config.js以便将来使用。
webpack.config.js
const path = require('path');
const webpack = require('webpack');
module.exports = {
entry: {
index:'./src/index.js'
},
output: {
filename: 'bundled.js',
path: path.resolve(__dirname, 'dist'),
publicPath:'dist/'
},
module: {
rules: [
{
test: /\.css$/,
loaders: ["style-loader","css-loader"]
},
{
test: /\.(jpe?g|png|gif)$/i,
loader:"file-loader",
options:{
name:'[name].[ext]',
outputPath:'assets/images/'
//the images will be emited to dist/assets/images/ folder
}
}
]
},
plugins: [
/* Use the ProvidePlugin constructor to inject jquery implicit globals */
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery",
"window.jQuery": "jquery'",
"window.$": "jquery"
})
]
};
application.js
require("@rails/ujs").start()
require("turbolinks").start()
require("@rails/activestorage").start()
require("channels")
require('webpack-jquery-ui');
import $ from 'jquery';
window.jQuery = $;
window.$ = $;
package.json
{
"name": "www",
"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",
"webpack-jquery-ui": "^2.0.1",
"tailwindcss": "^1.0.3",
"turbolinks": "^5.2.0"
},
"version": "0.1.0",
"devDependencies": {
"webpack-dev-server": "^3.7.0"
}
}
答案 0 :(得分:0)
如果您使用节点模块安装jquery,则路径“ jquery / src / jquery”表示安装在node_modules目录中的jquery,该目录的子目录为“ jquery / src”,其中包含jquery.js文件。
new webpack.ProvidePlugin({
$: 'jquery/src/jquery',
jQuery: 'jquery/src/jquery'
})
我用这个解决了我的问题。希望这会有所帮助。
参考:https://www.botreetechnologies.com/blog/introducing-jquery-in-rails-6-using-webpacker enter link description here