CodeNewbie Community

wasabigeek
wasabigeek

Posted on • Updated on • Originally published at dev.to

Asset Pre-compilation in Rails

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:
Ruby on Rails Frontend Pipeline

Why compilation?

Any moderately complex interactive web-app of today contains a lot of CSS and Javascript, so we smart developers devised extensions and frameworks to make them easier to manage, for example:

  • 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, transition is -webkit-transition in Safari).

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.

What is “production-ready”?

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

What are my options for pre-compilation?

Rails 6 actually has two mechanisms for compiling static assets:

  • The Asset Pipeline is the traditional way, using a gem called sprockets.
  • Webpack is has pretty much become a modern standard in the JS ecosystem, and Rails includes the webpacker gem 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/stylesheets should be where your CSS files go
  • /app/javascript/ should be where your JS files go

For the curious, here's some backstory on why there are two ways to compile assets, by Ross Kaffenberger.

How do I set up pre-compilation for production?

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).

Discussion (0)