【发布时间】:2020-08-01 13:04:14
【问题描述】:
我一直致力于将旧版 Rails 应用程序迁移到在 Rails 6.0.2 中使用 webpacker,但一直遇到 Uncaught ReferenceError: jQuery is not defined 错误。即使在我创建的新 Rails 6 应用程序中也会出现同样的错误。
我遵循了很多不同的教程/StackOverflow 答案,但似乎没有任何效果。这是我目前拥有的 - 谁能指出我正确的方向?
我已经运行了yarn add jquery,所以这是在我的package.json 文件中:
{
"name": "test_app",
"private": true,
"dependencies": {
"@rails/actioncable": "^6.0.0",
"@rails/activestorage": "^6.0.0",
"@rails/ujs": "^6.0.0",
"@rails/webpacker": "4.2.2",
"bootstrap": "^4.4.1",
"jquery": "^3.5.0",
"popper.js": "^1.16.1",
"turbolinks": "^5.2.0"
},
"version": "0.1.0",
"devDependencies": {
"webpack-dev-server": "^3.10.3"
}
}
在我的application.js 文件中:
require("@rails/ujs").start()
require("turbolinks").start()
require("@rails/activestorage").start()
require("channels")
require("jquery") // I've also tried without this line.
require("bootstrap");
在我的environment.js 文件中:
const { environment } = require('@rails/webpacker')
var webpack = require('webpack');
environment.plugins.append('Provide', new webpack.ProvidePlugin({
$: 'jquery/src/jquery', // I've also tried with just 'jquery' rather than referring specifically to the src folder.
jQuery: 'jquery/src/jquery' // Same comment as above.
}));
module.exports = environment
我很困惑为什么它不起作用 - 我已经尝试了建议的解决方案 here,以及大量其他资源。任何帮助将不胜感激!
【问题讨论】:
-
你能确定这个错误的来源吗?即,来自导入的库、
app/javascript/下的应用程序代码或视图中的<script>标记等。示例代码会有所帮助。 -
嗨@rossta,感谢您的回复!所以根本没有 jquery 工作 - 不是我保存在
app/javascript/src下的脚本,不是 jQuery 直接保存在我的 html.erb 文件中,也不是在 Chrome 控制台中运行$ === jQuery(我被告知将返回 true,如果jQuery 已加载)。所有结果都是Uncaught ReferenceError: jQuery is not defined或Uncaught ReferenceError: $ is not defined。 -
如果不将 jQuery/$ 暴露在全局范围内,它肯定不会在 Webpacker 之外工作(例如在模板和部分中)。我希望它可以在
app/javascript/src内工作,所以如果不是,您需要显示示例代码。 -
这一切看起来都不错。必须尝试重新启动服务器并硬重新加载?
标签: jquery ruby-on-rails webpack ruby-on-rails-6 webpacker