How do I use loadPath with sass-loader and webpack?

385 Views Asked by At

I'm creating a little app that is bundled with webpack. I'm using sass in the project and all scss files are located in a scss located in the root directory. I've got some partials I've created in a directory named partials. The directory structure looks like this:

directory structure of quiz app

At the top of the quiz.module.scss file, I have this:

@use "colors" as *;
@use "font";

I didn't want to write @use "partials/colors" and @use "partials/font", so I decided to include scss/partials in the list of loadPaths used by scss. I have this somewhere in my webpack.dev.js file:

const PATHS_TO_SASS_PARTIALS = ["scss/partials"]

and this somewhere else:

{
  test: /\.module\.scss$/,
  use: [
    {
      loader: "style-loader"
    },
    {
      loader: "css-loader",
      options: {
        modules: {
          mode: "local"
        }
      }
    },
    {
      loader: "resolve-url-loader"
    },
    {
      loader: "sass-loader",
      options: {
        sourceMap: true,
        sassOptions: {
          loadPaths: PATHS_TO_SASS_PARTIALS
        }
      }
    }
  ]
}

I think this should point webpack to load the _colors.scss file when I write @use "colors" as *; in a file like quiz.module.scss, but it isn't working. I get the following error when I run webpack-dev-server:

SassError: Can't find stylesheet to import.
  ╷
1 │ @use "colors" as *;
  │ ^^^^^^^^^^^^^^^^^^
  ╵
  scss\quiz.module.scss 1:1  root stylesheet

Am I doing something wrong or the loadPaths option doesn't work with sass-loader? I don't want to have to write @use "partials/colors". I was expecting that the loadPaths option will be passed by sass-loader to sass and the @use will work directly as mentioned above.

I read somewhere that sass load paths are evaluated relative to the path from which sass is called. That may be a reason for the error. I'm not sure. I'll just assume that since I'm starting webpack-dev-server from the root of the project on the command line, both sass-loader and sass would also be called from the same place.

Any kind of help would be really appreciated.

1

There are 1 best solutions below

0
violetflare On

The includePaths option is the correct one to use with sass-loader. This option allows you to specify directories for the loader to resolve @import declarations. Here's how you can use it:

{
    loader: 'sass-loader',
    options: {
        sassOptions: {
            includePaths: [path.resolve(__dirname, 'Develop', 'Styles')]
        }
    }
}

In this configuration, sass-loader will look in the Develop/Styles directory (relative to the directory of your webpack.config.js file) to resolve @import declarations in your Sass/SCSS files.