When creating a new rails project with Rails 6, it creates an application.html.erb with stylesheet_link_tag to load CSS and javascript_pack_tag for javascript files.
Now, rails 6 also provide a stylesheet_pack_tag, so my question is, when to use it? And if we use it, do we need to add all CSS files in app/javascript folder?
What is the best practice to load css, images with rails 6 and webpacker?
New Rails apps are configured to use webpack for JavaScript and Sprockets for CSS, although you can do CSS in webpack. You should choose Webpacker over Sprockets on a new project if you want to use NPM packages and/or want access to the most current JavaScript features and tools.
permalink #javascript_pack_tag(*names, defer: true, **options) ⇒ Object. Creates script tags that reference the js chunks from entrypoints when using split chunks API, as compiled by webpack per the entries list in package/environments/base.js.
Webpacker is a gem which allows easy integration of JavaScript pre-processor and bundler with Rails. It provides various helpers and configuration options to use webpack easily with Rails.
You should use stylesheet_pack_tag
if you are importing any CSS in Webpack AND if you have enabled extract_css: true
for any environment in config/webpacker.yml
.
Given the following directory structure:
app/
javascript/
packs/
application.js
styles/
site.css
And the following code in application.js
:
import '../styles/site.css'
You would use <%= stylesheet_pack_tag 'application' %>
in your view, i.e., the name of the stylesheet matches the name of the "pack".
At this point, I also recommend renaming app/javascript
to something like app/frontend
. So, the key changes in config/webpacker.yml
:
source_path: app/frontend
extract_css: true
app/
frontend/
packs/
application.js
styles/
site.css
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With