Webpacker 6: SCSS/Sass Loaders

Share:
Please consider sharing 🙏
Published At:
Dec 24th, 2020
Tags:
#rails, #webpacker, #tutorial, #sass
Next:
Webpacker 6: PostCSS Loaders
Previous:
Webpacker 6: Tailwind CSS 2.0 Integration

In order to process .scss and .sass files with Webpacker 6, you need to add sass-loader and sass.

Note: This section builds on the CSS section

Install

yarn add sass-loader sass

Usage

You should be able to use the same pack tag that you added for CSS.

Make sure you restart bin/webpack-dev-server after installing new loaders.

Style Loader Example

<%# app/views/layouts/application.html.erb %>

+ <%= stylesheet_packs_with_chunks_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
<%= javascript_packs_with_chunks_tag 'application', 'data-turbolinks-track': 'reload' %>

Extract Example

<%# app/views/layouts/application.html.erb %>

<%= javascript_packs_with_chunks_tag 'application', 'data-turbolinks-track': 'reload' %>
+ <%= stylesheet_pack_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
// app/javascript/packs/application.js

+ import "./application.scss"

Verify

Note: Make sure you restart the dev server!

Let’s create a new SCSS file:

touch app/javascript/packs/application.scss

Next, add some SCSS:

/* app/javascript/packs/application.scss */

$body-background: #fafafa;
$body-color: #444;

body {
  background: $body-background;
  color: $body-color;
  font-family: sans-serif;
}

h1,
nav,
footer {
  text-align: center;
}

main {
  margin: 4rem auto;
  max-width: 60rem;
}

Reload your browser and your styles should be applied now, and the Webpacker loader error should be gone.

View All Articles

Want to receive news and updates?