问题描述
我真的不敢相信让 JQuery 与 Rails 6 和 Webpacker 6 一起工作会如此困难。
Rails 6: How to add jquery-ui through webpacker? 中的建议似乎不起作用,但很难知道它是否是相同的代码堆栈。
我正在使用 Rails 6.1 和 Webpacker 6.0 的预发布版本来让 Heroku 很好地运行。哦,我的大部分“Javascript”都在 .coffee 文件中。
我什至尝试将 application.js 重命名为 application.coffee 并重新格式化,但也没有用。
我的 Gemfile 有
gem 'webpacker','~> 6.0.0.beta.6'
我已完成以下操作”
yarn add jquery jquery-ui-dist jquery-blockui
然后在webpacker 6 style中配置如下:
# config/webpacker/base.js
const { webpackConfig,merge } = require('@rails/webpacker')
const customConfig = require('./custom')
module.exports = merge(webpackConfig,customConfig)
# config/webpacker/custom.js
module.exports = {
resolve: {
alias: {
jquery: 'jquery/src/jquery',jquery_ui: 'jquery-ui-dist/jquery-ui.js'
}
}
}
和
# code/app/packs/entrypoints/application.js
global.$ = require("jquery")
require("jquery") // Don't really need to require this...
require("jquery-ui")
require("jquery-ui-dist/jquery-ui")
这都是来自包括这篇文章在内的许多来源的尝试的大杂烩 - Rails 6: How to add jquery-ui through webpacker?、https://github.com/rails/webpacker 和其他。
顺便说一下,我正在尝试从 Rails 5 迁移我的 Coffescript,因此这广泛使用了 JQuery $ global。
非常感谢任何帮助。
解决方法
按照给定文章中“更新”的答案进行操作。
https://gorails.com/forum/install-bootstrap-with-webpack-with-rails-6-beta
,首先在项目中加入JQuery:
yarn add jquery
然后添加到 config/webpack/environment.js
中的 webpack 插件:
const { environment } = require('@rails/webpacker')
const webpack = require('webpack')
environment.
plugins.
append(
'Provide',new webpack.ProvidePlugin({
$: 'jquery',jQuery: 'jquery'
})
)
就这样
在 webpacker 6.0 中,您可以使用其中一种方法:
- 直接更新
config/webpack/base.js
:
const { webpackConfig } = require('@rails/webpacker')
const webpack = require('webpack')
webpackConfig.
plugins.
push(
new webpack.ProvidePlugin({
$: 'jquery',jQuery: 'jquery'
})
)
module.exports = webpackConfig
- 使用自定义配置并将其合并到基础:
// config/webpack/base.js
const { webpackConfig,merge } = require('@rails/webpacker')
const customConfig = require('./custom')
module.exports = merge(webpackConfig,customConfig)
// config/webpack/custom.js
const webpack = require('webpack')
module.exports = {
plugins: [
new webpack.ProvidePlugin({
$: 'jquery',jQuery: 'jquery'
})
]
}
,
因此,在 mechnicov 的帮助下,我的最终解决方案是,正如他所建议的:
// config/webpack/base.js
const { webpackConfig,customConfig)
// config/webpack/custom.js
const webpack = require('webpack')
module.exports = {
resolve: {
alias: {
$: 'jquery/src/jquery',jQuery: 'jquery/src/jquery',jquery: 'jquery','jquery-ui': 'jquery-ui-dist/jquery-ui.js'
}
},plugins: [
new webpack.ProvidePlugin({
$: 'jquery',jQuery: 'jquery'
})
],// Eliminate CORS issue
devServer: {
host: 'localhost',port: 3000
}
}
# app/packs/entrypoints/application.js
// Make jQuery available everywhere
global.$ = require('jquery'),require('jquery-ui'),require('jquery-blockui')
...
我不知道这是否是最优雅的解决方案(解析、插件和 application.js 行都是必需的吗?),但它有效。
顺便说一句,还需要确保 webpacker gem 和相应的 yarn 模块都是 6.0.0.beta.6 版本(参见 https://github.com/rails/webpacker)
# Gemfile
gem 'webpacker','6.0.0.beta.6'
$ yarn add @rails/[email protected]