craco学习: 用 speed-measure-webpack-plugin 优化遇到的问题

speed-measure-webpack-plugin 这个插件在与 webpack5 配合时会报这个错: You forgot to add 'mini-css-extract-plugin' plugin
更新于: 2021-12-30 09:44:09
出错的截图

我的解决方案1

将 mini-css-extract-plugin 放在  smp.wrap(config) 之后

具体代码如下(我用的是 craco配置 cra 项目)

const Mini = require('mini-css-extract-plugin');
const one2extra = require('@jswork/one2extra').default;
const SpeedMeasurePlugin = require('speed-measure-webpack-plugin');
const smp = new SpeedMeasurePlugin();

module.exports = {
  // The Webpack config to use when compiling your react app for development or production.
  webpack: {
    configure: (webpackConfig) => {
      const [minPlugin, otherPlugins] = one2extra(
        (items) => items.findIndex((item) => item instanceof Mini),
        webpackConfig.plugins
      );
      webpackConfig.plugins = otherPlugins;
      webpackConfig = smp.wrap(webpackConfig);
      webpackConfig.plugins.push(minPlugin);
      return webpackConfig;
    }
  }
};
运行结果大概如上图

解决方案2

出现问题的原因其实是这个:刚更新的 react-scripts 里带的 webpack5 与现有的很多插件并不兼容

react-scripts 版本

解决办法就是降级为 4.0.3 这个稳定版本

  1. 降级 react-scripts 版本
  2. 删除  node_modules 目录
  3. npm i/yarn i 重装安装包

修改 package.json 文件

# 原来的
"react-scripts": "5.0.5",

# 降级后的
"react-scripts": "4.0.3",

这个出现的原因

在 craco 里的使用方式(webpack5目前不兼容),更加细节的可以看他的源码

const smp = new SpeedMeasurePlugin();
module.exports ={
  webpack: {
    configure: webpackConfig => (smp.wrap(webpackConfig))
  }
};

来自 mini-css-extract-plugin

https://github.com/webpack-contrib/mini-css-extract-plugin/issues/744

 

Please open an issue in speed-measure-webpack5-plugin, we can't fix it here, sorry. Also you don't need speed-measure-webpack5-plugin, webpack profile plugins/loader/etc by default

 

大体意思是:这个是 speed-measure-webpack-plugin 的问题,推荐你用 --profile,都 webpack 5了。

来自 speed-measure-webpack-plugin

https://github.com/stephencookdev/speed-measure-webpack-plugin/issues/167


解决办法1:降低 mini-css-extract-plugin 版本

same issue, apart from lowering the version of mini-css-extract-plugin to 1.3.6, or remove smp.wrap(),

is there no other better solution that make smp and mini-css-extract-plugin use the latest version at the same time?

# package.json

"dependencies": {
	"mini-css-extract-plugin": "1.3.6"
}

解决办法2:各种重新组装,让这两个插件的工作顺序正常

// webpack.config.js

const SpeedMeasurePlugin = require('speed-measure-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');

const config = {
  // ...
  plugins: [
    // Whatever other plugins you may have
  ]
};

const configWithTimeMeasures = new SpeedMeasurePlugin().wrap(config);
configWithTimeMeasures.plugins.push(new MiniCssExtractPlugin({}));

module.exports = configWithTimeMeasures;

参考