Search code examples
ruby-on-railswebpackruby-on-rails-6webpackerreact-rails

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


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?


Solution

  • 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).