How to Use jQuery in Rails 5.1+ with Yarn and Webpack

Feature thumb jquery rails

In Rails 5.1+, Rails no longer ships with jQuery by default, below are the steps you can follow for integrating the jQuery library into a new Rails application.

Installing Yarn Package Manager

If you are working on a Mac and have brew installed you can install Yarn with the following command:

brew install yarn

For installing on Linux or Linux based setup (C9, Nanobox, etc), here is a guide for installing yarn.

Generating a Rails Application with Webpack

You can build a new Rails application with the following command:

rails new DemoJsApp --webpack --database=postgresql -T

This will create a new Rails application that utilizes the Webpack tool to bundle JavaScript assets.

After the application is finished being created, change into the directory and create and migrate the database.

Use Yarn to Install jQuery into the Rails Application

From the root of the application, run the following yarn command:

yarn add jquery

You can confirm that this worked by opening the yarn.lock file that should have been generated at the root of the Rails application.

Now run the following rake command to install jQuery from Yarn into the application (you will need node installed on your system for this command to work properly):

rails yarn:install

Integrating jQuery into the Rails Application Codebase

With jQuery installed, now we need to require it in the application itself. Start by adding this gem to the Gemfile and then run bundle install:

gem 'jquery-rails'

Now open the app/assets/javascripts/application.js file and add //= jquery, and also swap out jquery_ujs for jquery_ujs. it should look like this:

Run the Webpack Installer

Now we can run the Webpack installer with the command:

rails webpacker:install

Testing the Installation

We can test that everything was installed and working properly by creating a test page with the following command:

rails g controller Pages home

Assuming that everything is working, you can run the Rails server and navigate to:

http://localhost:3000/pages/home

And you should see the default screen and if you open the browser's JavaScript console you shouldn't see any errors. Now let's add some sample content to the homepage, such as:

We can now test out some jQuery code with the following script in app/assets/javascripts/pages.coffee:

If everything is setup, you should now be able to watch the container fade out when the button is clicked, which means that jQuery is working and installed properly!

Deployment on Heroku (Optional)

If you're deploying to Heroku with this setup, you'll need to use custom buildpacks so that webpack works properly, you can run the following commands to set the buildpacks up properly:

Full Application Source Code: