$ is not defined when installing jQuery in Rails via Webpack

alopez02 picture alopez02 · Apr 29, 2019 · Viewed 7.5k times · Source

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 despite being able to compile jQuery.

I've added jQuery with yarn add jquery, so my package.json looks like this

{
  "name": "muladeseis_app",
  "private": true,
  "dependencies": {
    "@babel/preset-react": "^7.0.0",
    "@rails/actioncable": "^6.0.0-alpha",
    "@rails/activestorage": "^6.0.0-alpha",
    "@rails/ujs": "^6.0.0-alpha",
    "@rails/webpacker": "^4.0.2",
    "babel-plugin-transform-react-remove-prop-types": "^0.4.24",
    "jquery": "^3.4.0",
    "prop-types": "^15.7.2",
    "react": "^16.8.6",
    "react-dom": "^16.8.6",
    "turbolinks": "^5.2.0"
  },
  "version": "0.1.0",
  "devDependencies": {
    "webpack-dev-server": "^3.3.1"
  }
} 

My app/javascript/packs/application.js is requiring jquery from node_modules

require("@rails/ujs").start()
require("turbolinks").start()
require("@rails/activestorage").start()
require("channels")
require("jquery")

And I've tried to register $ in config/webpack/environment.js by doing:

const { environment } = require('@rails/webpacker')

const webpack = require('webpack')

module.exports = environment

environment.plugins.append(
    'Provide',
    new webpack.ProvidePlugin({
        $: 'jquery',
        jQuery: 'jquery'
    })
)

Whenever I add a script in my views with a $ reference I get Uncaught ReferenceError: $ is not defined.

I've checked in StackOverflow answers like this to see if I'm registering incorrectly the key character '$' but I've found only answers suggesting using the ProvidePlugin which I'm already referring to in my configuration.

Also if I explore my app Sources in the browser inspector I do see jQuery code integrated in localhost:3000 >> packs/js so the issue is not that Webpack is not finding jQuery but that the key words '$' and 'jQuery' are not recognised.

I'd appreciate your help debugging this.

Answer

alopez02 picture alopez02 · Apr 30, 2019

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.