webpacksasssass-loader

Webpack 5 sass-loader not compiling nested scss files


I am setting up Webpack for my first time and I am getting stuck on the Sass part.

I have a file structure like this:

test.scss has this in it:

$blue: dodgerblue;

body {
  background-color: $blue;
}

index.scss has this:

@import url("./styles/utilities/test.scss");

my entry file is index.js and below if I use the import in #1 it works, the scss compiles correctly, but if I use the import in #2 it does not compile.

  1. import './styles/utilities/test.scss';
  2. import './index.scss';

The output for #1 looks like this:

body {
  background-color: dodgerblue;
}

The output for #2 looks like this:

body {
  background-color: $blue;
}

Why is this happening? Ultimately, I would like to be able to organize my stylesheets in different folders and be able to compile all of them into css.

my webpack.config.js looks like this:

const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const path = require('path');

module.exports = {
  entry: './src/index.js',
  output: {
    filename: 'index.js',
    path: path.resolve(__dirname, 'assets'),
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['@babel/preset-env']
          }
        },
      },
      {
        test: /\.scss$/i,
        use: [
          MiniCssExtractPlugin.loader,
          "css-loader",
          {
            loader: "postcss-loader",
            options: {
              postcssOptions: {
                plugins: {autoprefixer: {}}
              }
            }
          },
          "sass-loader"
        ]
      }
    ],
  },
  plugins: [new MiniCssExtractPlugin({
    filename: "index.css"
  })],
  resolve: {
    extensions: ['.js', '.scss']
  }
};

Solution

  • I just figured it out. We should be using Sass Modules instead of @import. Also, this video helped me a lot: https://www.youtube.com/watch?v=CR-a8upNjJ0

    When I replaced @import with @use it started working.