Grayscale profile picture

Patrique Ouimet

Senior Product Engineer

Setting up Webpack in Ruby on Rails

Tue, Nov 20, 2018 8:30 AM

Introduction

This is a simple introduction on how I setup Webpack in Ruby on Rails. I hope it'll be useful to others who wanted to use Webpack within a Rails application like I did.

Caveats

This article assumes you've already setup a rails project via rails new {project-name}

Setting Up Sprockets

After setting up a new project you'll have files in app/assets/javascripts, delete any files in this directory. We will be using it as the output directory for Webpack. You may also add app/assets/javascripts if you don't want to check in your compiled javascript.

New Directory and Entry File for Webpack to use

Now create a new directory where you will write all the JavaScript to be compiled by Webpack, so this article we will use:

mkdir -p app/frontend/javascripts

Then create the entry point file:

touch app/frontend/javascripts/entry.js

Add something to the file to test it is working:

console.log('Loaded with Webpack!');

Installing Webpack

Create a file named package.json in the root of your project, then add the following:

{
    "name": "my-app",
    "dependencies": {},
    "devDependencies": {}
}

Now install webpack and webpack-cli:

npm i webpack --save-dev
npm i webpack-cli --save-dev

Setup Webpack Config

Create a file in your project root directory named webpack.config.js and add the following:

module.exports = {
    entry: './app/frontend/javascripts/entry.js',
    output: {
        filename: './app/assets/javascripts/app.js',
        path: __dirname
    }
}

Compiling Assets

Now to compile assets simply run:

npx webpack --mode=development

Configuring Rails

Now we need to make Rails aware of the assets we just compiled, to do so add the following to your config/initializers/assets.rb:

Rails.application.config.assets.precompile += %w( app.js )

This tells Rails that we have a file named app.js that can be loaded via Sprockets

Loading Assets with Sprockets

Now to load assets in your mark up with Sprockets simply use:

<%= javascript_include_tag 'app' %>

Test it!

Run your rails application (i.e. rails server) visit the page the assets are loaded in open the console and you should see:

Loaded with Webpack!

Conclusion

I had to go through this exercise for a new project of mine so I thought I would share, I hope this has helped someone!

Notes

This is NOT a production config, this is a bare minimum setup, for production please consider the following and do your own research:

  • You should use a minifier/uglifier to minimize the loaded content
  • You should have an environment variable which determines what to run (development vs production) or even separate configs
  • You should likely also run your CSS (SASS, LESS, POSTCSS, etc.) through the same process

Gist