Best way to import single css files in a rails 6 views using webpack
Asked Answered
C

1

5

So i already imported the application.scss with the tags

<%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' %>
<%= stylesheet_pack_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>

and it works

however i want to separate my css files and call them in specific views like in the home/index view call

<%= javascript_pack_tag 'home/index', 'data-turbolinks-track': 'reload' %>
<%= stylesheet_pack_tag 'home/index', media: 'all', 'data-turbolinks-track': 'reload' %>

ive achieved this creating a separate js file such as home.js and inside just importing my home.scss like this

import '../../stylesheets/home/index'

my question is, is this the correct way?

do i always have to create a js file to import my css file?

is there a better aproach?

Cherice answered 1/3, 2020 at 2:33 Comment(0)
A
6

Yes, it's possible. You don't need to create a separate JS file, just create a CSS "pack" for each view:

app/javascript
└── packs
    ├── application.js
    └── home.scss

In your view:

<%= javascript_pack_tag 'home', 'data-turbolinks-track': 'reload' %>
<%= stylesheet_pack_tag 'home', media: 'all', 'data-turbolinks-track': 'reload' %>

Demo app, branch with change: https://github.com/rossta/rails6-webpacker-demo/compare/example/css-pack

Caveats:

  1. Using multiple "packs" per page (e.g. 'application' and 'home') is not typically recommended (a) in Webpacker 5. Webpack has no way of knowing that you want to share code between packs unless you add special configuration to do so (see footnote). My answer above assumes you're not duplicating imports across bundles (or you're ok with duplication).

  2. Webpack will still create a JavaScript bundle to load your CSS bundle so you'll still need both javascript_pack_tag and stylesheet_pack_tag

a. You can share code across bundles by using the splitChunks API (Webpacker 5 docs, enabled by default in Webpacker 6).

Artieartifact answered 10/3, 2020 at 2:12 Comment(3)
Just want to add to OP example: you can separate only the CSS or JS in packages. In my case, the JS file was unique for all and a different CSS file for admin views and users views.Thief
@rossta, just a heads up that the link to splitChunks API docs is dead. Also, question: do you think the "refrain from multiple packs per page from happening recommendation" still holds even with webpacker v6 example of <%= javascript_pack_tag 'calendar', 'map' %> ?Currey
@Currey Link fixed, thanks. Correct, my recommendation was true for Webpacker v5, but now splitChunks is turned on by default in recent Webpacker v6 release candidates. In theory, developers shouldn't have to think about the multiple packs problem as much. There are still some limitations/potential problems to be aware of, currently tracked as issues in the Webpacker repo.Artieartifact

© 2022 - 2024 — McMap. All rights reserved.