Adding JQuery in Ruby on Rails 6 Applications

As any Ruby on Rails developer knows, webpacker was a major addition in Rails 6. With the introduction of webpacker, Rails applications no longer need asset pipeline. The app/assets/javascript is moved to app/javascript.

With this update, packages like JQuery are added differently than they were before. This article will discuss how to add JQuery in a Rails 6 application.

1
rails new jquery

Now run the following command:

1
yarn add jquery

In app/javascript/packs/application.js, add the following code:

1
2
3
4
5
6
7
8
const webpack = require('webpack')
environment.plugins.prepend('Provide',
 new webpack.ProvidePlugin({
   $: 'jquery/src/jquery',
   jQuery: 'jquery/src/jquery'
 })
)

Add the following line to app/javascript/packs/application.js to require jquery:

1
require('jquery')

Now you are all set to use JQuery in a Rails 6 application!