Rails 6 comes with Sprockets and Webpacker by default. Confusing, right?
Let me tell you a secret: You don’t need both. Just use Webpacker.
Legacy applications and older gems still use Sprockets to serve assets. This was done to add backwards compatibility. If you don’t have a good reason to keep Sprockets around, don’t.
Advantages of Webpack(er):
- You can easily import npm packages to take care of your frontend needs
- Most tools from the JS ecosystem will target Webpack users anywway
- You’ll only need to debug one asset bundling tool instead of two!
If we take a look at what the Elixir folks are doing, they use Webpack by default on Phoenix Applications. This is great because it keeps things straightforward, specially when you need to debug something.
Watch out for these two situations before making this decision:
- You have a large legacy Rails application with a complicated frontend that depends heavily on Sprockets. See section Huge Legacy Apps below to learn more.
But if you’re ready to ditch Sprockets in favor of Webpacker, here’s a list of good resources for new and small apps, up to huge legacy ones:
New or Small Rails Apps: Keep it Webpacker-only
If you’re creating a new Rails app, do youself a favor and just skip generating anything related to Sprockets:
$ rails new myapp --no-sprockets
If you have an existing app, this guide is perfect for people who are in a hurry or not doing anything crazy on the frontend side of things.
Medium-sized apps: Move everything over to Webpacker
This other tutorial is very similar but goes over a couple of extra things and gives some tips about Polyfills and deployment.
Huge Legacy Apps: Keep Sprockets Working While Migrating to Webpacker
Impossible? Maybe not! Check out this example of a successful migration:
This is an in-depth post explaining how a team gradually switched from Sprockets to Webpacker on a larger Rails App. They had to support both Webpacker and Sprockets to maintain backwards compatibility. They go over the challenges and how they were able to solve the issues that popped up.
Their approach had 3 distinct phases:
Read this when you’re not sure if you should make the move or not.
Plan for these types of migrations when you have a complex frontend or legacy gems that rely on Sprockets.
The best way to go about it is by gradually moving assets to Webpacker while keeping the existing asset pipeline intact until you get rid of Sprockets completely. This process will take a while, be ready for it.
And always make sure you have good tests!
Did you like this article? Then you're gonna love these other ones: