Ruby on Rails Q & A


How to use Webpacker in Rails?

Webpacker is the official gem introduced in Rails to integrate the powerful JavaScript module bundler, Webpack, into the Rails application. It allows developers to handle JavaScript, CSS, and assets in a modern way, leveraging the power of Webpack. Here’s how you can use Webpacker with Rails:


  1. Installation: If you’re starting a new Rails application, Rails 6 and onwards include Webpacker by default. However, if you want to add Webpacker to an existing application, you can do so by running `rails webpacker:install`.


  1. Directory Structure: Webpacker introduces a new directory: `app/javascript/`. This is where all your JavaScript code, stylesheets, and assets managed by Webpack reside. The pack files, which are the entry points for Webpack compilation, are located in `app/javascript/packs`.


  1. Including JavaScript in Views: To use the JavaScript compiled by Webpacker in your Rails views, you include it using the `javascript_pack_tag`. For instance, to include the `application.js` pack, you would add `<%= javascript_pack_tag ‘application’ %>` to your view or layout file.


  1. CSS & Assets: Webpacker isn’t just for JavaScript. You can also manage stylesheets and images using Webpack. By default, styles can be placed in the same `app/javascript/` directory and then imported into your JavaScript files. Likewise, images can be imported in your JavaScript and used seamlessly.


  1. Extensions & Plugins: Webpacker makes it easy to incorporate modern JavaScript tools and frameworks, like React, Vue, and Angular. By using commands such as `rails webpacker:install:react`, you can swiftly set up the necessary configurations and directory structures.


  1. Development: During development, you can run `./bin/webpack-dev-server` to start the Webpack dev server, which will recompile your assets on the fly as you make changes. This is especially helpful for seeing real-time changes without having to manually compile assets.


Webpacker offers a streamlined way to integrate modern frontend tooling with the Rails ecosystem. It bridges the gap between Rails’ asset pipeline and the modern JavaScript toolchain, providing developers with a robust solution to manage frontend assets in a Rails application.

Previously at
Flag Argentina
time icon
Senior Software Engineer with a focus on remote work. Proficient in Ruby on Rails. Expertise spans y6ears in Ruby on Rails development, contributing to B2C financial solutions and data engineering.