Introducing jQuery in Rails 6 Using Webpacker

jQuery in Rails 6

As we all know that first release candidate of Rails 6 is out with exciting features and refinements in existing features. Today we will look into one of those features, which is webpacker. It is now by default in Rails 6 as a Javascript Compiler.

What is Webpacker?

Webpacker is a gem that allows packing assets using modern tools like yarn and writing the latest flavor of JavaScript via Babel.

It makes it easy to use the JavaScript preprocessor and bundler Webpack to manage application-like JavaScript in Rails.

What is Webpack?

Webpack is a module bundler.

When we bundle webpack in a project, it traverses the imports, constructing a dependency graph of the project and then generates the output based on the configuration.

What’s Babel then?

Babel functions same as SASS compiler works for .sass and .scss files. It is a JavaScript transpiler that converts edge JavaScript into plain old ES5 JavaScript that can run in any browser (even the old ones).

Rails 6 jQuery upgrade with webpacker! Read more.

For Rails 6 – Webpacker is the Default Javascript Compiler

In the previous version of rails, we have to generate an application with – webpacker option for the integration of webpack. But now webpacker is the default and a good replacement of sprockets.

Webpacker gem

Further Reading: Rails 6: Action Mailbox — Explained. Why?How? When?

Some new Defaults of Rails 6

  1. Javascript has been removed from app/assets directory!
  2. Javascript moved to app/javascript/packs
  1. javascript_include_tag is replaced by javascript_pack_tag
  1. No more using jquery-rails gem!!!

Now, How we will use Jquery in Rails 6??

In our Rails application run below command to add jQuery.

$ yarn add jquery

It will save the dependency of jquery to our application.

  1. Now to verify jquery is installed or not, check below files
    • package.json => "jquery": "^3.3.1",
    • yarn.lock => jquery@^3.3.1:
  2. Add below code in environment.js

Now, our file looks like,

The path ‘jquery/src/jquery’ indicates the jquery installed in node_modules directory having sub directory ‘jquery/src’ and which contains jquery.js file there.

Require jquery in application.js file.

require('jquery')

Voila! Now you should be able to use jquery in your Rails 6 application.


At BoTree Technologies, we build enterprise applications with our Ruby on Rails team of 35+ engineers.

Consulting is free – let us help you grow!

Related posts

Best Project Management Methodology for Ruby on Rails App Development in 2022

byParth Barot
3 years ago

Top Things to Know about .NET 6

byParth Barot
2 years ago

Track User Events and Visits in Rails using Ahoy GEM!

bySanjay Prajapati
6 years ago
Exit mobile version