How To Use jQuery In Rails 5.2 Using Webpack

Jan 17 2018

As you may have heard, starting in Rails 5.1, jQuery is no longer added by default to new Rails applications. Since I’ve just started recently building a new app on Rails 5.2, I encountered the inevitable situation where I wanted to use jQuery for something. Since I’m already on the webpack/webpacker bandwagon, I wanted to see how to go about incorporating jQuery into my webpack setup.

I had a couple goals in mind:

  • Load jQuery via webpack along with all of my other javascript dependencies
  • Make jQuery available to all of my javascript modules without having to import or require it everywhere

It was pretty straightforward, but I couldn’t find a single place that had all of the steps involved, so here it is.

Add jQuery via Yarn

yarn add jquery

Update webpack config

Add jQuery to your webpack config, making it available for $, jquery and jQuery.

config/webpack/environment.js

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

module.exports = environment

environment.plugins.prepend(
  'Provide',
  new webpack.ProvidePlugin({
    $: 'jquery',
    jQuery: 'jquery',
    jquery: 'jquery'
  })
)

The main section to be added is to tell webpack to provide the jQuery plugin to all of the javascript modules using ProvidePlugin from webpack.

Bask in jQuery glory

Here is a little snippet from my foray into the Stimulus javascript framework, using jQuery to access one of the elements.

app/javascript/src/controllers/shippable_controller.js

import { Controller } from "stimulus"

export default class extends Controller {
  toggle() {
    if (this.checkbox.checked) {
      $(this.fields).removeClass("hidden");
    }
  }

  get fields() {
    return this.targets.find("fields");
  }

  get checkbox() {
    return this.targets.find("checkbox");
  }
}

Want More Helpful Tips?

Tips on coding, design and running a software business

Questions/Comments?

Hit me up on twitter @joeybeninghove