Angular CLI 6自定义Webpack SCSS加载器

时间:2018-09-21 00:29:28

标签: webpack sass angular-cli angular-cli-v6

我正在尝试编写一个自定义Webpack模块,以用cli 6覆盖或扩展角度6中的当前SCSS构建,目的是能够传递“品牌”并将其与任何替代匹配,例如“ somemodule / 'brand'/ filename.override.scss”并替换父文件夹“ somemodule / filename.scss”中的文件,但我没有任何进展。

设置: @ angular / cli”:“ 6.2.2”,带有 @ angular-builders / custom-webpack“:” ^ 2.4.1“

我已经更新了项目构建,以反映出我正在使用自定义Webpack以及覆盖/扩展的位置

     "build": {
      "builder": "@angular-builders/custom-webpack:browser",
      "options": {
        "customWebpackConfig": {
          "path": "./extra-webpack.config.js"
        },

我的extra-webpack.config.js看起来像这样,只是我在许多网站上看到的一种基本的hello世界风格

module.exports = {
    module:{
        rules: [{
            test: /\.scss$/,
            use: [{
                loader: "style-loader"
            }, {
                loader: "css-loader"
            }, {
                loader: "sass-loader",
                options: {
                    includePaths: ["src"]
                }
            }]
        }]
    }
};

但是以此运行我的构建

ng run websitename:build

引发此错误

    Module build failed (from ./node_modules/sass- 

loader / lib / loader.js):

^                                                                                        
  Invalid CSS after "": expected 1 selector or at- 
 rule, was "var content = requi"    

据我了解,这可能是尝试重新定义scss规则时引起的,但是我看不到要删除的对此规则的任何其他引用。我还尝试了一些方法来完全覆盖旧规则,但是没有运气。

我主要关注的解决方案和指南 https://dev.to/meltedspark/customizing-angular-cli-6-buildan-alternative-to-ng-eject-1oc4 https://medium.com/a-beginners-guide-for-webpack-2/webpack-loaders-css-and-sass-2cc0079b5b3a https://www.npmjs.com/package/@angular-builders/custom-webpack#custom-webpack-config-object https://github.com/webpack-contrib/sass-loader/blob/master/test/bootstrapSass/webpack.config.js https://github.com/webpack-contrib/sass-loader/issues/536 https://github.com/meltedspark/angular-builders

1 个答案:

答案 0 :(得分:0)

我遇到了同样的问题,我尝试了mergeStrategies但没有用。我将自定义webpack更改为一个函数,解决了该问题,我能够扩展sass选项。

module.exports = function(config) {
    const rules = config.module.rules || [];
    rules.forEach(rule => {
        if (String(rule.test) === String(/\.scss$|\.sass$/)) {
        const loaders = rule.use;
        const transformedLoaders = loaders.map(l => {
            if (l.loader === 'sass-loader') {
                // here you can override options or replace or add.
            } 
            return l;
        });
        rule.use = transformedLoaders;
        }
    });
    return config;
};