Adding jQuery to Rails 6 using webpackerUsing jQuery in Rails 6.0 with webpacker

iMango Admin

Let’s keep it simple.

This article describes only on how to add jQuery using webpacker.

Assuming that you have an Rails 6 application with webpacker installed, run the following command from the root of the directory.

yarn add jquery

This will add dependencies in package.json and yarn.lock.

We need to make changes to webpack configuration, by editing the file config/webpack/environment.js.

// config/webpack/environment.js

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

const webpack = require('webpack')
  new webpack.ProvidePlugin({
    $: 'jquery/src/jquery',
    jQuery: 'jquery/src/jquery'

module.exports = environment

It points to the jQuery in node_modules. Add those lines just before exporting that module.

Now feel free to add jQuery to javascript packs in application.js.

// app/javascript/packs/application.js


That’s it. Now our application is succesfully integrated with jQuery.

Wasn’t that simple enough?

Looking for a First-Class Business Plan Consultant?