Webpack with Rails, Part 2:
Precompile Harder

Warning: This post is very old. It may be out of date, and links in it may not work. Continue at your own risk.

Note: This article is more generally about how to add dependencies to a Rake task, and why you might want to do that.

If you followed my previous article on webpack and Rails, you might have built yourself a trendy little React app. Then you tried to deploy it, and that didn’t work, did it?

Wait, what are you on about?

Whether you’re doing artifact-based deploys, git deploys, or something else altogether, at some point something is going to run rake assets:precompile. This will work but miss your webpack generated assets, because unless you checked your compiled entries in (please, tell me you didn’t do that) they won’t exist when the rake task is run because webpack never did its thing.

The best solution, rather than to modify your deploy system, is to add a dependency to the assets:precompile rake task that runs webpack. This is the correct thing to do (though it might look like a hack) because the assets:precompile doesn’t actually do it’s job properly if you haven’t run webpack first. It really does depend on webpack.

Adding a Dependency to Rake Task

You can add a dependency to a rake task just by redefining it without a block, and passing dependencies just like you normally would.

# lib/tasks/assets.rake

namespace :assets do
  task :precompile => :webpack
end

task :webpack do
  sh "npm install"
  sh "./node_modules/.bin/webpack"
end

Ship it.

I provide technical leadership, risk assessment, project planning, training, and additional development to software teams. If you need help taking a project from idea through execution, get in touch.