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:
<%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>
<%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
Webpacker then added two new directives:
<%= javascript_pack_tag 'application' %>
<%= stylesheet_pack_tag 'application' %>
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:
<%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
<%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' %>
It’s using sprockets for CSS, and webpacker for Javascript. I think this makes the most sense for Rails, but the back and forth transition hasn’t been smooth for me.
One change made to config/initializers/assets.rb
is the configuration line:
Rails.application.config.assets.paths << Rails.root.join('node_modules')
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.
Comments or Questions? Let me know how your experience went below.