A Quick and Easy Guide to the Asset Pipeline in Rails 7
Rails 7 ships with a new way of handling assets, which seems so confusing that you might wonder if it's a feature.
Let's break it down and make some sense of it.
Here are three reasons why the new asset pipeline is worth looking into:
- No more asset bundling
- No more Webpack nonsense
- No more NodeJS
Even though there are many options, the end goal is to simplify asset management.
If you want the video version of this post, here it is.
The big new feature that makes it all possible is HTTP2. It removed the performance penalty for sending many small files over the network.
So now you don't have to create one big file. In fact, that might be less performant in some cases.
The browser can now fetch asset files based on pages visited, as opposed to everything. It can also re-fetch only the files that changed, making caching even more effective.
How does the asset pipeline work?
The asset pipeline is a collection of components that work together. Here's a list of what they might be.
Concatenation for merging together many files into one big file.
Minification for compressing the contents of a file to make it smaller in size.
Fingerprinting to force reloading of asset changes (i.e., cache busing).
These features are available through one or more gems.
The asset pipeline gems
The sprockets gem is the oldest of the bunch providing an all-in-one solution. But it's still used in Rails7 because it's stable and offers two critical features.
Those features are:
- fingerprinting, and
asset:precompilecommand required by some of the hosting platforms.
A newer and simpler gem exists that will replace sprockets, called propshaft. Propshaft enables a faster pipeline by delegating to other specialized tools.
Check out the importmap-rails gem.
I made a video about import maps, so check it out if you want to learn more.
When it comes to CSS, the cssbundling-rails gem makes it easy to use your favorite framework.
It provides installers for TailwindCSS, Bootstrap, Bulma, PostCSS, and Dart Sass. But it requires a bundling tool.
If you want to use TailwindCSS without a bundling tool, there's the tailwindcss-rails gem.
How to install Bootstrap
To install Bootstrap in your project, you have two options.
If you're starting from scratch, it's pretty easy. You start your project with the
-j esbuild --css bootstrap options and that's it.
But if you're migrating from import maps, you might want to check out the How to Install Bootstrap in Rails 7 article where I show you how to fix a problem with the installer.
As you can see, there's no one tool for everything. You can pick the right tool for your needs and build your pipeline.