[英]Issue loading jQuery in Webpacker 5
I'm trying to add jQuery as a Webpacker/Webpack (5.4.3) plugin to my Rails (6.0.4.1) app, but I keep getting a "jQuery is not defined error."我正在尝试将 jQuery 作为 Webpacker/Webpack (5.4.3) 插件添加到我的 Rails (6.0.4.1) 应用程序中,但我不断收到“jQuery 未定义错误”。 I'm using the following code, which seems to be the general answer to this question on most searches:
我正在使用以下代码,这似乎是大多数搜索中这个问题的一般答案:
// config/webpack/environment.js
const { environment } = require('@rails/webpacker')
const webpack = require('webpack')
environment.plugins.prepend(
'Provide',
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
jquery: 'jquery'
})
)
module.exports = environment
Now, I CAN get it working using the following code:现在,我可以使用以下代码使其工作:
// application.js
import $ from 'jquery/dist/jquery.js';
globalThis.jQuery = $;
globalThis.$ = $;
I'm fairly new to Webpack/Webpacker, so I'm mostly just trying to understand why the top solution won't work.我对 Webpack/Webpacker 相当陌生,所以我主要是想了解为什么顶级解决方案不起作用。 Thanks!
谢谢!
The provider module automatically loads the module, but , it is made available only within the files that are actually ES Modules . provider 模块会自动加载模块,但是,它仅在实际上是ES Modules的文件中可用。 ES Module is a JS file containing at least one
import
or export
statement or a file ending with .mjs
extension. ES 模块是一个 JS 文件,包含至少一个
import
或export
语句或一个以.mjs
扩展名结尾的文件。
environment.plugins.prepend(
'Provide',
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery'
})
);
The above code will make identifiers $
and jQuery
available within any ES Module whenever Webpack encounters these free identifiers in your code.每当 Webpack 在您的代码中遇到这些免费标识符时,上面的代码将使标识符
$
和jQuery
在任何ES 模块中可用。 In other words, the ProvidePlugin
doesn't really modify the global scope .换句话说,
ProvidePlugin
并没有真正修改全局范围。
Inside your application.js
file, you will need to do what you have done:在你的
application.js
文件中,你需要做你已经完成的事情:
globalThis.jQuery = $;
// or
window.jQuery = $;
And your application.js
file should have at least one import
or export
statement not necessarily the jQuery import statement.并且你的
application.js
文件应该至少有一个import
或export
语句,不一定是jQuery import 语句。 Alternately, if you do not like it then, you can also consider using expose-loader .或者,如果您不喜欢它,您也可以考虑使用Exposure-loader 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.