In the previous post, we talked about what a frontend is, and briefly looked at how it works in Rails. Now, we'll look specifically at pre-compilation:
- webpack does a lot of things, one of them being the bundling of our numerous CSS and JS files (which we break up for ease of development) into fewer files that are faster to load
autoprefixer lets us write CSS without having to worry about vendor-prefixes (some browsers named CSS properties differently as they were experimental at the time etc. For example,
These make it more convenient (once you get past the learning curve) to work on our frontend, but this means our assets usually can't be used in their raw form - Rails has to convert them into the actual HTML, JS and CSS files before sending it to your browser.
In local development, the
rails server will mostly do this conversion on the fly for you. But in production, you'll want to pre-compile production-ready assets, so the server can focus on generating and sending pure HTML.
This includes things like:
- Combining separate JS and CSS files into less files so a browser needs to make less requests
- Minifying (compressing) the files so they’re smaller and load faster
- Fingerprinting so the browser knows when to ignore its cached files and request for the latest ones
Rails 6 actually has two mechanisms for compiling static assets:
- The Asset Pipeline is the traditional way, using a gem called
Webpack is has pretty much become a modern standard in the JS ecosystem, and Rails includes the
webpackergem to enable this.
You can actually just pick one or the other, but it seems the Rails-recommended way is to use Webpacker for JS files, and the Asset Pipeline for everything else e.g. CSS.
A brand new Rails 6 project loads with that in mind, so:
/app/assets/stylesheetsshould be where your CSS files go
For the curious, here's some backstory on why there are two ways to compile assets, by Ross Kaffenberger.
If you’re deploying with Heroku it will do all the pre-compilation for you, unless you've customised your build process. For other services, you'll have to run
rake assets:precompile in your deployment scripts. See the Rails guide for more details.
Next, we'll take a look at the different options for styling our web-sites/apps (i.e. CSS).