$ is not defined when installing jQuery in Rails via Webpack $ is not defined when installing jQuery in Rails via Webpack ruby-on-rails ruby-on-rails

$ is not defined when installing jQuery in Rails via Webpack


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.


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 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.