Rails live reloading assets

a_chris

Christian

Posted on June 2, 2022

Rails live reloading assets

Recently I've been trying to learn more about the Rails assets pipeline. The standard documentation is very well written and has tons of tips and best practices but there's something I was still missing: live reloading the assets, in particular the css/scss assets.

Working with React this is the pretty standard behaviour: you update a file and you can instantly see the changes on the browser.

The Rails documentation does not explain how to obtain this behaviour and, honestly, I've never managed to make the live compilation work, so I've been killing the server, running bundle exec rails assets:precompile and restarting the server the whole time, until now.

Luckily, a few days ago I discovered an handy gem that solves this issue in a very simple way: rails_live_reload.

Image description

Install the rails_live_reload

Adds this gem in the development group, or whatever group you need, in you Gemfile



group :development do
  gem 'rails_live_reload'
  ...
end


Enter fullscreen mode Exit fullscreen mode

and un bundle install.

Tweak the development settings

Open the config/environments/development.rb file and add these lines:



config.assets.compile = true
config.assets.digest = false


Enter fullscreen mode Exit fullscreen mode

the assets.compile option enables the live compilation through Sprockets, as stated in the official documentation while the assets.digest turns off the generation of digest strings for the assets names. To be honest I'm not sure why the latter is required but if it is omitted both the live reloading and the live compilation won't work.

Run the css watch

We need to open a terminal window and spawn the process that watches for changes in the the css/scss files.
If you are using the dartsass-rails gem you can run:



bundle exec rails dartsass:watch


Enter fullscreen mode Exit fullscreen mode

while if you are using cssbunding-rails or any other solutions you probably want to run:



yarn build:css --watch


Enter fullscreen mode Exit fullscreen mode

keep this terminal running, do not kill it.

The Rails server

Finally, open a new terminal and run the Rails server to enjoy the live reloading assets 😎.

Feel free to write any suggestion or question in the comments. I would be really happy if someone could explain to me, and everyone who will read this tutorial, why the config.assets.digest = false is required to make the auto compilation/reloading work 🤯

💖 💪 🙅 🚩
a_chris
Christian

Posted on June 2, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related