react编写项目引入npm包打包时,总会将一些npm包重复打包的不同的js文件中,可以使用splitChunks 进行拆分,降低体积,加快速度
1、安装
npm install customize-cra webpack-bundle-analyzer
2、修改启动命令,在package.json中修改
"scripts": {
"start": "react-app-rewired start",
"build": "react-app-rewired build",
"test": "react-app-rewired test",
"eject": "react-app-rewired eject"
},
3、在项目根目录下新建config-overrides.js 文件,在里面如下配置
const { override } = require("customize-cra");
const { BundleAnalyzerPlugin } = require("webpack-bundle-analyzer");
// View packaging size
const analyzer = () => (config) => {
if (config.mode === "production") {
config.plugins.push(new BundleAnalyzerPlugin());
}
return config;
};
module.exports = override(
analyzer(), //打包后可以查看项目中重复引用的npm包,方便底下拆分
(config) => {
config.optimization.splitChunks = {
cacheGroups: {
reactDom: {
chunks: "all",
test: /(react-dom)/, //只是示例,可以自己根据需要调整
name: "reactDom",
priority: 100,
enforce: true,
},
},
};
return config;
});
配置完成,快去试试效果
浙公网安备 33010602011771号