Back to Blog

Webpack in the Rails Asset Pipeline

This snippet of code integrates Webpack into the Sprockets build process

Rails applications have long had a unilateral asset compilation strategy provided by Sprockets (as a part of Ruby on Rails's Asset Pipeline). However, as the depth of JavaScript build tools increases, application authors can and should take advantage of more diverse asset combination techniques than what Sprockets is designed to provide. This can lead to better long-term maintainability through modularity of frontend components (which is all the rage these days).

At Brigade, we wanted to integrate the Webpack module bundler to combine our CommonJS modules.

However, we also wanted to keep the Sprockets as the last step in our build pipeline for the easy integration with Rails via the asset_path helpers.

We ended up creating a prerequisite step in the asset precompilation process by using a bit of Rake trickery. It has been working pretty well for us, and perhaps you will find it useful:

# lib/tasks/assets.rake
# The webpack task must run before assets:environment task.
# Otherwise Sprockets cannot find the files that webpack produces.

namespace :assets do
  # In this task, set prerequisites for the assets:precompile task
  task :compile_environment => :webpack do

  desc 'Compile assets with webpack'
  task :webpack do
    sh '$(npm bin)/webpack --config webpack.config.js'

  task :clobber do
    rm_rf "#{app.config.root}/app/assets/javascripts/{bundle.js,components.js}"