解决 Webpack 打包警告 WARNING in entrypoint size limit exceeded
分析 Webpack 构建报 bundle size limit exceeded 诱因,详解 splitChunks 代码分割与动态懒加载方案。
问题现象
在打包前端工程时,控制台大量标黄报警:
WARNING in asset size limit: The following asset(s) exceed the recommended size limit (244 KiB).
Assets: js/app.bundle.js (2.8 MiB)
WARNING in entrypoint size limit: The following entrypoint(s) combined asset size exceeds the recommended limit (244 KiB).
触发根因
所有第三方庞大依赖(如 lodash、echarts、moment、three.js)全部被一股脑打包进了单个主入口文件 app.bundle.js 中,导致首屏 JS 超过 2MB。
解决方案
在 webpack.config.js 中配置 splitChunks 拆分公共代码
module.exports = {
optimization: {
splitChunks: {
chunks: 'all',
maxInitialRequests: Infinity,
minSize: 20000,
cacheGroups: {
vendor: {
test: /[\/]node_modules[\/]/,
name(module) {
const packageName = module.context.match(/[\/]node_modules[\/](.*?)([\/]|$)/)[1];
return `npm.${packageName.replace('@', '')}`;
},
},
},
},
},
};
验证方法
重新打包,超大 JS 被精准拆分为多个数十 KB 的并行小包,警告完全平息,首屏加载速度提升数倍。


