Quickly Add Legacy jQuery to a Modern Rails App

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

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")

Done!