Search code examples
webpackglobal-variablescss-modulessass-loader

Resolving SCSS global variables with Webpack


I'm having trouble getting my scss global variables file to resolve. I'm trying to add a scss color file which I can simply import globally wherever it's needed.

Webpack 1 config:

  module: {
    loaders: [
      {
        test: /\.scss$/,
        loader: 'style' +
        '!css' +
          '?sourceMap' +
          '&modules' +
          '&importLoaders=1' +
          '&localIdentName=[local]__[hash:base64:4]' +
        '!sass' +
          '?sourceMap'
      }
    ]
  },
  sassLoader: {
    includePaths: [
        path.resolve(__dirname, '../src/<path to stylesheets>/themes')
      ]
  },

Sass File

@import "colors";

.add {
  background: $button-inactive-state;
}

Error Code (some personal items redacted)

./~/css-loader?sourceMap&modules&importLoaders=1&localIdentName=[local]__[hash:base64:4]!./~/sass-loader/lib/loader.js?sourceMap!./src/<path to file>/toggle-item-button/item-icon.scss
Module build failed: 
@import "colors";
^
      File to import not found or unreadable: colors
Parent style sheet: stdin
      in /Users/<me>/Checkouts/<my project>/src/<path to file>/toggle-item-button/item-icon.scss (line 1, column 1)
Error: 
@import "colors";
^
      File to import not found or unreadable: colors
Parent style sheet: stdin
      in /Users/<me>/Checkouts/<my project>/src/<path to file>/toggle-item-button/item-icon.scss (line 1, column 1)
  at options.error (/Users/<me>/Checkouts/<my project>/node_modules/node-sass/lib/index.js:286:26)

 @ ./src/<path to file>/toggle-item-button/item-icon.scss 4:14-229

Solution

  • I found a working solution:

    Webpack Config:

      resolve: {
        alias: {
          themes: path.resolve(__dirname, '../src/<path to stylesheets>/themes')
        },
      },
    

    SCSS

    @import "~themes/colors";