Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use stylesheet_pack_tag instead stylesheet_link_tag with Rails 6

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?

like image 504
Sanjay Prajapati Avatar asked Mar 01 '20 04:03

Sanjay Prajapati


People also ask

Why use webpacker in Rails?

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.

What is javascript_ pack_ tag in Rails?

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.

What does webpacker do?

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.


1 Answers

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
like image 88
rossta Avatar answered Oct 13 '22 06:10

rossta