【问题标题】:How to use 'extract-text-plugin' in my webpack setup如何在我的 webpack 设置中使用“extract-text-plugin”
【发布时间】:2017-07-18 16:11:49
【问题描述】:

我一直在尝试理解 webpack 中的“生产模式”。从我现在在 webpack 2 中收集的内容来看,您可以运行 webpack -p 但这似乎并不丰富。 我从 Webpack 1 继承的设置是这样的:

var config = {
context: __dirname + '/app',
entry: './index.js',
output: {
    path: __dirname + '/app',
    filename: 'bundle.js'
},
plugins: [
    new CompressionPlugin({
        asset: "[path].gz[query]",
        algorithm: "gzip",
        test: /\.js$|\.html$/,
        threshold: 10240,
        minRatio: 0.8
    }),
    new webpack.ProvidePlugin({
        moment: "moment"
    }),
    new webpack.ProvidePlugin({
        $: "jquery",
        jQuery: "jquery"
    })
],
module: {
    loaders: [
        {
            test: /\.js$/,
            loader: 'babel-loader',
            exclude: /node_modules/
        },
        {
            test: /\.scss$/,
            loader: 'style-loader!css-loader!sass-loader',
            exclude: /node_modules/
        },
        {
            test: /\.html$/,
            loader: 'raw-loader',
            exclude: /node_modules/
        }
    ]
}
};

if (process.env.NODE_ENV === 'production') {
    config.output.path = __dirname + '/dist';
    config.plugins.push(new webpack.optimize.UglifyJsPlugin());
    config.plugins.push(new ExtractTextPlugin("styles.css"));
    config.module.loaders({
        test: /\.scss$/,
        use: ExtractTextPlugin.extract({
            fallback: "style-loader",
            use: "style-loader!css-loader!sass-loader"
        })
    })
}

module.exports = config;

我真正想要的是在生产模式下使用extract-text-plugin,我尝试了以下操作:

if (process.env.NODE_ENV === 'production') {
    config.output.path = __dirname + '/dist';
    config.plugins.push(new webpack.optimize.UglifyJsPlugin());
    config.plugins.push(new ExtractTextPlugin("styles.css"));
    config.module.loaders({
        test: /\.scss$/,
        use: ExtractTextPlugin.extract({
            fallback: "style-loader",
            use: "style-loader!css-loader!sass-loader"
        })
    })
}

我收到以下错误:

config.loaders({
           ^
TypeError: config.loaders is not a function

【问题讨论】:

    标签: webpack webpack-2 extract-text-plugin


    【解决方案1】:

    config.module.loaders 是一个数组,因此您需要像使用插件一样推送。但是你最终会得到.scss 的两个加载器配置,这显然不是你想要的。相反,您可以定义一个传递给配置的变量,如下所示:

    // Default SCSS loader
    var scssLoader = 'style-loader!css-loader!sass-loader';
    if (process.env.NODE_ENV === 'production') {
      // Overwrite it with the extract-text loader
      scssLoader = ExtractTextPlugin.extract({
        fallback: "style-loader",
        use: "style-loader!css-loader!sass-loader"
      })
    }
    

    然后配置中的.scss 规则将变为:

    {
      test: /\.scss$/,
      loader: scssLoader,
      exclude: /node_modules/
    },
    

    【讨论】:

      猜你喜欢
      • 2017-07-11
      • 2018-07-26
      • 2018-10-18
      • 2017-03-08
      • 2018-01-26
      • 2017-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多