I\'m trying to install jQuery in Rails 6.0.0.rc1 via Webpack and I\'m not sure what I\'m missing but I\'m getting the error $ is not defined
in the browser console
I tried a lot of things and some worked and some didn't, and some didn't work in my Docker container. In the end I settled on putting this in app/javascript/packs/application.js
:
global.$ = require('jquery')
You need to do yarn add jquery
of course.
I'm sure there are better ways but this is the only thing that worked for me so I'm putting it up here in case it helps anyone else.
i was trying to upgrade from rails 4 to rails 6. After few hours of debugging , finally i fixed this jQuery loading error.
So here are the steps, I followed :
yarn add jquery
yarn add expose-loader
const { environment } = require('@rails/webpacker')
environment.loaders.append('jquery', {
test: require.resolve('jquery'),
use: [{
loader: 'expose-loader',
options: '$',
}, {
loader: 'expose-loader',
options: 'jQuery',
}],
});
module.exports = environment
require("@rails/ujs").start()
require("turbolinks").start()
require("@rails/activestorage").start()
require("channels")
require("jquery");
bin/webpack-dev-server
Always restart webpack-dev-server, if you update environment.js file.
if you want to use older version of jQuery (Ex: version 2.1.4 )
yarn add jquery@2.1.4
The code in config/webpack/environment.js
should look like this:
environment.plugins.prepend('Provide',
new webpack.ProvidePlugin({
$: 'jquery/src/jquery',
jQuery: 'jquery/src/jquery'
})
)
see also https://www.botreetechnologies.com/blog/introducing-jquery-in-rails-6-using-webpacker
I've got what's missing.
In app/javascript/packs/application.js
forgot to declare:
window.jQuery = $;
window.$ = $;
So jQuery keywords could be picked up.
This solution worked for me with Rails 6.0.2.2
and yarn 1.16.0
https://stackoverflow.com/a/54906972/2970582