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

21,486

Solution 1

Found. Actually you can configure sass-loader in webpack.config.json, as described here : https://github.com/jtangelder/sass-loader

Here is the relevant part :

sassLoader: {
   includePaths: [path.resolve(__dirname, "./some-folder")]
}

Solution 2

If you use Create React App v3 which allows absolute imports you can use the tilde

@import "~theme/colors";

Solution 3

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

Solution 4

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 {
  //...
}

Solution 5

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
}
Share:
21,486
bdavidxyz
Author by

bdavidxyz

Javascript, Rails, and test guy. But team first.

Updated on May 27, 2021

Comments

  • bdavidxyz
    bdavidxyz almost 3 years

    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