一起使用 mini-css-extract-plugin 和 style-loader

spe*_*naz 9 webpack mini-css-extract-plugin

我是 webpack 的新手,并遵循一些教程来学习基础知识。

我想style-loader在开发过程中注入样式表(启用 HMR)并希望MiniCssExtractPlugin用于生产构建。但是当我使用 MiniCssExtractPlugin 插件时,我失去了样式加载器的注入功能。

请查看我的 webpack 配置:

const webpack = require('webpack');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const path = require('path');

module.exports = {
    entry: ['./src/index.js'],
    output: {
        filename: 'app.js',
        path: path.resolve(__dirname, 'dist')
    },
    module: {
        rules: [
            {
                test: /\.(js|jsx)$/,
                exclude: /node_modules/,
                use: {
                    loader: "babel-loader"
                }
            },
            {
                test: /\.(sass|scss)$/,
                use: [
                    "style-loader",
                   {
                        loader: MiniCssExtractPlugin.loader,
                        options: {
                            hmr: process.env.NODE_ENV === 'development'
                        }
                    },
                    "css-loader",
                    "sass-loader"
                ]
            }
        ]
    },
    plugins: [
        new webpack.HotModuleReplacementPlugin(),
        new MiniCssExtractPlugin({
            filename: '[name].css',
            chunkFilename: '[id].css'
        })
    ],
    devServer: {
        contentBase: path.join(__dirname, 'dist'),
        compress: true,
        hot: true,
        port: 3000
    }
};
Run Code Online (Sandbox Code Playgroud)

小智 6

在分配了功能的第二个参数webpack.config.js,以module.exports包含模式标志(--mode [development|production])。所以在这里你可以使用模式来加载MiniCssExtractPlugin.loaderstyle-loader

在开发时,使用style-loader比每次提取样式都快。但是在生产中,您应该将样式提取到单独的文件中,以避免 Web 中的加载故障,当样式在 HTML 之后加载时,您会暂时看到没有样式的页面。

module.exports = (_, { mode }) => ({
  // other options here
  module: {
    rules: [
      // other rules here
      {
        test: /\.s?css$/i,
        use: [
          mode === 'production'
            ? MiniCssExtractPlugin.loader
            : 'style-loader',
          'css-loader',
          'sass-loader'
        ],
      },
    ],
  },
});
Run Code Online (Sandbox Code Playgroud)

  • 请添加一些关于答案中的代码的作用以及为什么它应该解决问题的解释 (2认同)

Ber*_*oer 3

MiniCssExtractPlugin 说实际上你不能这样做:

该插件只能在加载器链中没有样式加载器的生产版本中使用,特别是如果您想在开发中使用 HMR。