• July 15, 2020
  • 1 min read

Custom directory for Webpacker in Rails apps

Starting from Rails 6, Webpacker is the default JavaScript compiler for Rails apps.

By default, Rails recommends adding the Webpacker related JavaScript code in app/javascript directory. A lot of people wanted to place the JavaScript code in custom directory instead of app/javascript. It is now possible to customize it.

You just need to set the source_path in the config/webpacker.yml to the directory relative to the app folder where you want to place the Webpacker JavaScript code.

# config/webpacker.yml

default: &default
  source_path: app/frontend

This change is available in Webpacker gem from version 4.1.0 onwards and in Rails from Rails 6.0.1 onwards.

With this change, we can place our JavaScript code in any of the custom directory of our choice under the app directory, configure it via the source_path setting in the webpacker.yml and that's it.

Once we have configured this directory, then the subsequent Webpacker commands use this directory as reference.

✗ bundle exec rails webpacker:install:react
Copying babel.config.js to app root directory
       force  babel.config.js
Copying react example entry file to /Users/prathamesh/Projects/fun/frontend_rails_app/app/frontend/packs
      create  app/frontend/packs/hello_react.jsx
Updating webpack paths to include .jsx file extension
      insert  config/webpacker.yml

Want to know more about Webpacker and Rails, check out my other blog posts on this topic or subscribe to my newsletter.

Leave a comment