我正在从使用 Assets 管道迁移到Rails 5.2中的webpacker。我的AJAX响应都在浏览器控制台的rails-ujs.js错误中导致Uncaught ReferenceError: $ is not defined
。
我已经设置了我的webpacker环境以包含jquery。
const { environment } = require('@rails/webpacker');
const webpack = require('webpack');
environment.plugins.append("Provide", new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
Popper: ['popper.js', 'default']
}));
module.exports = environment;
我已经在我的../packs/application.js中导入了rails-ujs和turbolinks
import Rails from 'rails-ujs'
import 'activestorage'
import 'bootstrap'
...
import Turbolinks from "turbolinks"
Rails.start();
Turbolinks.start();
// Import application specific stuff
import 'application/javascripts'
然后,当请求完成时,我尝试添加一个类。类似于导轨中显示的内容
https://guides.rubyonrails.org/working_with_javascript_in_rails.html#server-side-concerns
我的show.js.erb文件看起来像这样
$("#result").addClass("active")
我得到一个错误
Uncaught ReferenceError: $ is not defined
at <anonymous>:1:1
at processResponse (rails-ujs.js:282)
at rails-ujs.js:195
at XMLHttpRequest.xhr.onreadystatechange (rails-ujs.js:263)
最佳答案
同时,我发现自己做错了什么。我需要配置一个别名。我在文档https://github.com/rails/webpacker/blob/master/docs/webpack.md#configuration中找到了解决方案
将environment.config.set('resolve.alias', {jquery: 'jquery/src/jquery'});
添加到我的/config/webpacker/environment.js
中就可以了。
const { environment } = require('@rails/webpacker');
const webpack = require('webpack');
environment.plugins.append("Provide", new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
Popper: ['popper.js', 'default']
}));
environment.config.set('resolve.alias', {jquery: 'jquery/src/jquery'});
module.exports = environment;