Adding JQuery To Your Rails 6 App

In this quick tutorial, we will run down how to add JQeury to a Rails 6 app.

Rails 6 has seen many improvements and one of them is that webpacker is the default engine to deploy many of the add on services and libraries in a Rails app, like JQuery.

Add JQuery Via Yarn

Enter the terminal inside your app and run the command below.

rails-app$ yarn add jquery

Then add this code to your config/webpack/environment.js file:

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

Your environment file will look like this, when it is complete:

// config/webpack/environment.js

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

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

module.exports = environment

Then you need to add the following to your app/javascript/packs/application.js file:

require('jquery')

For example, here's how my application.js file looked on a recent app using Jquery:

// app/javascript/packs/application.js

require("@rails/ujs").start()
require("turbolinks").start()
require("@rails/activestorage").start()
require("channels")
require("jquery") // Tailwind CSS import "stylesheets/application" // Font Awesome import "@fortawesome/fontawesome-free/js/all";

After that, you will be able to use JQuery in your Rails 6 app.

0 Comments


Please log in to leave a reply.