-->

Webpack sass loader does not recognize global vari

2020-08-12 06:16发布

问题:

i have this sass directory:

- _vars.scss
- main.scss

//vars.scss

$base-container: 1400px;

//main.scss

@import './vars';

In other js file i have:

require('./some-module-sass-file');

//some-module-sass-file.scss

.container {
  width: $base-container;
}

The problem is i have global variables in the vars file and the some-module-sass-file not recognize them and throw an error:

undefined variable $base-container

回答1:

You have to import the vars file into every Sass partial that uses those variables, because every partial is compiled on its own; none of the files will 'know about' the others unless you specifically import them.

If you don't want to have to type the imports in every Sass file, you can look at baggage-loader, which will automatically add them for you.



回答2:

Without using sass-resources-loader:

Thanks to @Arseniy-II for helping me get to this answer, in conjunction with this thread: https://github.com/webpack-contrib/sass-loader/issues/218

Using loader options in your webpack module rules, you can assign a data property to sass-loader, you should then be able to use all sass functions as expected:

module: {
  rules: [
    // Apply loader
    {
      test: /\.scss$/,
      use: [
        'style-loader',
        'css-loader',
        {
          loader: 'sass-loader',
          options: {
            data: '@import "path/to/global.scss";',
            includePaths:[__dirname, 'src']
          },
        },
      ],
    },
  ],
}


回答3:

Short answer:

https://github.com/shakacode/sass-resources-loader

Long answer:

sass-resources-loader allow to use variables, mixins etc in each required sass file.

So you can have your variables in vars.scss:

$main: #073288; 
$secondary: #F6A906;

And then use them as usual:

.my-component {
    background-color: $main;
    color: $secondary;
}

All you need to do is

  1. Install sass-resources-loader: npm install sass-resources-loader --save-dev

  2. And configure you webpack.config:

{
    loader: 'sass-resources-loader',
    options: {
        resources: './path/to/vars.scss'
    }
}

Here is example from github

module: {
  rules: [
    // Apply loader
    {
      test: /\.scss$/,
      use: [
        'style-loader',
        'css-loader',
        'postcss-loader',
        'sass-loader',
        {
          loader: 'sass-resources-loader',
          options: {
            resources: ['./path/to/vars.scss', './path/to/mixins.scss']
          },
        },
      ],
    },
  ],
}

If you have problems with path to resources try to use path like this:

  • const path = require('path')
  • resources: [path.resolve(__dirname, './../vars.scss')]
  • __dirname is avaliable inside you webpack.config without requiring it.