Rails 6, Webpacker, and jQuery

Quickly add jQuery to your Rails 6 application using Webpacker

Posted by Curtis Miller Curtis Miller

I'm finally getting around to using Rails 6 (hooray for legacy projects!) and learning about some of the differences. One of those, I encountered was how to add jQuery to our application.

Most of our legacy projects include the jquery-rails gem. You might be able to guess how old those projects are! Looks like the new, preferred way is to use yarn to add JavaScript dependencies. No problem!

From the root of your Rails directory run:

yarn add jquery

You should now see jquery listed in your package.json file. Awesome! Now let's add it to /app/assets/javascripts/application.js. What do you mean that file doesn't exist??

Okay, so our JavaScript files have moved from /app/assets/javascript to /app/javascript/packs and there's a new way to include them in your views using javascript_pack_tag instead of javascript_include_tag. Right, no problem.

In /app/javascript/packs/application.js add jQuery to your list of requires:

require("jquery")

Just one last thing we need to do to be able to use jQuery, though. In your /config/webpack/environment.js file add:

const webpack = require('webpack')
environment.plugins.prepend('Provide',
  new webpack.ProvidePlugin({
    $: 'jquery/src/jquery',
    jQuery: 'jquery/src/jquery'
  })
)

This should go just before the line that exports the environment. Think of this file as similar to your Rails /config/environment.rb, in that it contains the common JS stuff across all environments. You may notice that there are per environment JS files (development.js, production.js, test.js) there as well to allow you to specify JS per environment.

You should be all set to use jQuery in your Rails app now. If I missed anything, let me know in the comments!



Velocity Labs

Need web application development, maintenance for your existing app, or a third party code review?

Velocity Labs can help.

Hire us!