[webpack踩坑路之]css提取插件mini-css-extract-plugin和speed-measure-webpack-plugin冲突

2022-11-21 11:30:48 浏览数 (1)

当我们使用webpack5.x打包项目时,在现网环境需要使用mini-css-extract-plugin将我们的样式打包到独立的样式文件中,使用官方推荐配置能正常运行

代码语言:javascript复制
const MiniCssExtractPlugin = require("mini-css-extract-plugin");

module.exports = {
  plugins: [
    new MiniCssExtractPlugin({
      // Options similar to the same options in webpackOptions.output
      // all options are optional
      filename: "[name].css",
      chunkFilename: "[id].css",
      ignoreOrder: false, // Enable to remove warnings about conflicting order
    }),
  ],
  module: {
    rules: [
      {
        test: /.css$/,
        use: [
          {
            loader: MiniCssExtractPlugin.loader,
            options: {
              // you can specify a publicPath here
              // by default it uses publicPath in webpackOptions.output
              publicPath: "../",
            },
          },
          "css-loader",
        ],
      },
    ],
  },
};

但是当我们同时使用了 speed-measure-webpack-plugin 插件来打印各个module的打包时间时,就会出现无法正常打包的情况,报错信息如下:

代码语言:javascript复制
Webpack 5 fails as soon as I smp.wrap() my config, with the following error:

ERROR in ..../Error.scss
Module build failed (from ../../node_modules/mini-css-extract-plugin/dist/loader.js):
Error: You forgot to add 'mini-css-extract-plugin' plugin (i.e. `{ plugins: [new MiniCssExtractPlugin()] }`), please read https://github.com/webpack-contrib/mini-css-extract-plugin#getting-started
    at Object.pitch (.../node_modules/mini-css-extract-plugin/dist/loader.js:50:14)

这时候我们需要去判断下,再不需要输出打包时间的情况下,不使用 smp 插件,如,我的方式

代码语言:javascript复制
const wrapConfig = isDev ? smp.wrap : (config) => config;
module.exports = wrapConfig({

})

0 人点赞