How to use absolute path to import custom scss, when using react + webpack?

Viewed 25361

Inside a scss file, I'm trying to import custom, widely used chunk of scss (in a React/SASS/Webpack stack).

So that I can use a shared mixin.

Let's say I'm creating an MyAdminButton and I want to import scss file that concerns all the buttons of the project. (It's custom scss, not vendor/external one).

It would look like this :

//this actually works but it is a code smell : what if the current file moves ?
@import "../../stylesheets/_common-btn-styles.scss";

.my-admin-btn {
    // here I can use a shared mixin defined in _common-btn-styles.scss
}

This sounds not good since if my scss file move, then everything is broken.

Thanks for your help

6 Answers

In react-scripts latest version you can add a .env file at the project root with the variable SASS_PATH=node_modules:src.

To specify more directories you can add them to SASS_PATH separated by a : like path1:path2:path3

official doc

You could add stylesheets to the Webpack modules with resolve.modules

// webpack.config.js
const path = require('path')

module.exports = {
  // ...
  resolve: {
    modules: [
      'node_modules',
      path.join(__dirname, 'path/to/stylesheets'),
    ],
  },
}

And sass-loader allows you to import _common-btn-styles.scss from the modules. https://webpack.js.org/loaders/sass-loader/#resolving-import-at-rules

@import "~_common-btn-styles.scss";

.my-admin-btn {
  // Use the shared mixins
}

Webpack 5

Configuration is different for webpack 5 as includePaths should be specified in the option sassOptions:

// Webpack config
{
  test: /\.scss$/,
  loader: 'sass-loader',
  options: {
    sassOptions: {
      includePaths: [path.resolve(__dirname, '<path to styles>')],
    },
  },
},

Webpack 4

I had to do so more research to solve this issue using other answers so here is my working solution:

// Webpack config
{
  test: /\.scss$/,
  loader: 'sass-loader',
  options: {
    includePaths: [path.resolve(__dirname, '<path to styles>')],
  },
},

Then in your scss file:

@import 'filename.scss'; // Imported from <path to styles> folder.

.style {
  //...
}

If using the Dart Sass implementation with sass-loader, the options are slightly different.

The options for sassOptions are here

sassOptions: {
...
  loadPaths: [path.resolve(__dirname, '../src/')],
}
Related