如何配置sass-loader以仅从SCSS生成CSS

时间:2018-09-26 22:11:35

标签: webpack sass sass-loader

我正在尝试在webpack.config中使用2个模块 除了构建js包外,我想构建网页的CSS,但总是出错

ERROR in ./src/sass/company-style.scss 1:3
    Module parse failed: Unexpected token (1:3)
    You may need an appropriate loader to handle this file type.
    > h1 {
    |   color: #c43f4c; }

company-style.scss

$myred: #c43f4c;
h1 {
  color: $myred;
}

请问以下清单中的cssConfig。我不明白如何正确配置加载程序

webpack.config.js

const path = require('path')
var config = {
    // common Configuration
    module: {
        rules: [
            {
                test: /\.js$/,
                exclude: /(node_modules|bower_components)/,
                use: {
                    loader: 'babel-loader',
                }
            }
            ,{
                test: /\.scss$/,
                use: [{
                    loader: 'style-loader'
                }, {
                    loader: 'css-loader'
                }, {
                    loader: 'sass-loader'
                }]
            }

            ,{
                test: /\.(png|svg|jpg|gif)$/,
                use: [
                    {
                        loader: 'file-loader'
                    }
                ]
            }
        ]
    }

};

var bundleConfig = Object.assign({}, config, {
    name: "js-bundle",
    entry: './src/index.js',
    output: {
        filename: 'bundle.js',
        path: path.resolve(__dirname, 'dist')
    }
});
var cssConfig = Object.assign({}, config,{
    name: "css-bundle",
    entry: "./src/sass/company-style.scss",
    output: {
        filename: "company-style.css",
        path: path.resolve(__dirname, 'dist')
    },

    module: {
        rules: [
            {
                test: /\.scss$/,
                exclude: /(node_modules|bower_components)/,
                /*use: [{
                    loader: 'sass-loader'
                }]*/
                use: ['sass-loader']
            }
        ]
    }
});
module.exports = [
    bundleConfig, cssConfig
];

bundleConfig 模块没有问题。 bundle.js已构建并正常运行

2 个答案:

答案 0 :(得分:2)

如果我正确理解了这个问题,那么您想从SCSS文件中生成一个独立的CSS文件。

看看mini-css-extract-plugin

const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const devMode = process.env.NODE_ENV !== 'production'

module.exports = {
  plugins: [
    new MiniCssExtractPlugin({
      // Options similar to the same options in webpackOptions.output
      // both options are optional
      filename: devMode ? '[name].css' : '[name].[hash].css',
      chunkFilename: devMode ? '[id].css' : '[id].[hash].css',
    })
  ],
  module: {
    rules: [
      {
        test: /\.(sa|sc|c)ss$/,
        use: [
          devMode ? 'style-loader' : MiniCssExtractPlugin.loader,
          'css-loader',
          'postcss-loader',
          'sass-loader',
        ],
      }
    ]
  }
}

答案 1 :(得分:0)

我从未见过这样的组合式装载机,您是否尝试过类似的方法?

{{1}}