Adding jQuery to a Rail 6 App using Webpacker

Although jQuery is not recommended for modern Rails UI development, it is often necessary to support basic functionality, legacy functionality, or be able to prototype quickly.

TO be clear, if you do install jQuery and also a modern UI environment like React, Vue.js, or Angular, do not mix the two.

A section or page of your website done in React should not be manipulated by jQuery under any circumstances.

Here’s a quick way to add jQuery to a modern Rails app via yarn package manager.

Add jQuery for Rails 6

Step 1 Add jQuery to your package.json via yarn

yarn add jquery

Step 2: Modify environments.js

Go to config/webpack/environment.js and add this code in between the existing two lines.

const webpack = require('webpack')
environment.plugins.prepend('Provide',
  new webpack.ProvidePlugin({
    $: 'jquery/src/jquery',
    jQuery: 'jquery/src/jquery'
  })
)

The complete environment.js file looks like so (the part you are adding is shown in purple.)

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

const webpack = require('webpack')
environment.plugins.prepend('Provide',
  new webpack.ProvidePlugin({
    $: 'jquery/src/jquery',
    jQuery: 'jquery/src/jquery'
  })
)

module.exports = environment

If environment.plugins.prepend(‘Provide

Step 3: Modify application.js

Add require("jquery") to your app/javascript/packs/application.js file so it looks like so (shown in purple.)

The change code is shown in red.

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

Step 4: Confirm Your Work

Note that modern browsers will respond to the symbol $ as a Javascript function that calls to native code. This means that if you are running jQuery with $, you may see strange errors if your jQuery isn’t actually initialized.

You can easily tell if it is by opening the web console in your browser. Note you will want to check both the short symbol $ and also the object jQuery itself— when properly installed, they are synonyms of each other (both are ways to call jQuery).

When they are NOT properly installed, you get this result:

For $, you see Chrome return this ƒ $() { [native code] }

f $() { [ native code] }

for jQuery, you will get an error:

VM32:1 Uncaught ReferenceError: jQuery is not defined

VM113:1 Uncaught ReferenceError: jQuery is not defined

When it is correctly installed, you will instead see the jQuery object returned by the web console when you type both $ and jQuery. This is how you can confirm that it is correctly installed. Here, it is shown in Chrome web console with $ and then, on the next line, the jQuery keyword itself. As you can see, both return the actual jQuery function, shown here as jQuery = function jQuery(selector, context) with a comment about how jQuery does some loopy stuff to initialize itself.