Categories

Meta

Using CSS in Rails 6

Published February 20, 2020 by john

I’ve been finally moving some of my Rails applications from Rails 5.2 to Rails 6 and I always seem to get caught up on the webpacker CSS locations. It’s not uncommon to spend a lot of time figuring out where the CSS went, and why it’s not being served.

Pre-webpacker, there were two sprockets directives for adding Javascript and CSS to your site:

If you add your Javascript and CSS into your app/javascripts folder, you need to be sure to import your css directly, and then tell webpacker to compile the CSS. I think in order to mitigate the clunkiness of this setup and to help the transition from Sprockets to Webpacker, a new rails 6 app uses the following directives:

This means that Sprockets will look for CSS or images in your node_modules directory.

This is great! For something like ActionText, which is built on Trix, your app needs both CSS and Javascript. I always thought it wasn’t the best to include CSS with Javascript, as it didn’t feel very much like the Rails way, or to cumbersomely copy and paste CSS from the Javascript modules into the CSS folders. This current setup seems like the best of both worlds.

This is a small change, but it will hopefully simplify the relationship between Javascript and CSS in your app, especially as the transition to webpacker continues for every Rails app.