Skip to content

Instantly share code, notes, and snippets.

@jarednorman
Last active February 19, 2017 20:48
Show Gist options
  • Save jarednorman/1ca9cf52cbcb02ba6324 to your computer and use it in GitHub Desktop.
Save jarednorman/1ca9cf52cbcb02ba6324 to your computer and use it in GitHub Desktop.
Webpack with Rails Part 2: Precompile Harder

Webpack with Rails Part 2: Precompile Harder

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment