How to @import external SCSS properly with webpack and Vue.js?

后端 未结 2 1085
情书的邮戳
情书的邮戳 2021-02-05 11:56

As in Material Component Web\'s example, I want to be able to import SCSS from my node_modules like this:

@import \'@material/elevation/mdc-elevatio         


        
2条回答
  •  轮回少年
    2021-02-05 12:13

    Got it.

    here's a part of my webpack 2 config's module.rules:

    {
      test: /\.(sass|scss)$/,
      use: [
        'style-loader',
        'css-loader',
        {
          loader: 'sass-loader',
          options: {
            includePaths: [path.resolve(__dirname, 'node_modules')],
          },
        },
      ],
    },
    

    So what did I do wrong? My options object was placed in the rule directly, not the loader.

    The old webpack config rule looked like this:

    {
      test: /\.(sass|scss)$/,
      use: ['style-loader', 'css-loader', 'sass-loader'],
      options: { includePaths: [path.resolve(__dirname, './node_modules')] },
    },
    

    See the difference? Instead of the 'sass-loader' string, I extended it to an object, containing the loader name and the options object, because the options only apply to the sass-loader.

    (You could also drop the path.resolve and only write 'node_modules', but it might be safer to leave it.)

    Check out this documentation page for further information. https://webpack.js.org/configuration/module/#rule-use

    Without that loader, you must prefix each import with a ~, which webpack converts to the node_modules folder, at least with my previous configuration. But this will break 3rd party SCSS frameworks like Material Components Web, because they use @import statements without a leading ~ themselves, for example here.

    Inside .vue files

    This will not work in .vue files, as vue-loader just uses sass-loader without any options by default. So if you want that to work, you probably need to make use of vue-loader's own options, as described in its documentation.

    (I'm unable to get it to work for some reason I don't know...)

提交回复
热议问题