Webpack4 splitChunks如何抽离两个React懒加载组件的公共共享代码?
Webpack splitChunks 配置调整方案
问题原因
你当前配置的所有缓存组仅匹配了工具库、UI组件库、第三方依赖等特定路径的代码,没有覆盖业务代码中被多个懒加载chunk共享的模块,因此两个组件共用的Filter模块会分别打入两个组件的独立chunk中,不会被单独抽离。
调整后的配置
splitChunks: { chunks: 'all', maxInitialRequests: Infinity, minSize: 0, cacheGroups: { utlis: { name: "utlis", test: /[\\/]app[\\/]utils[\\/]/, chunks: 'all', }, ant_design: { name: "ant_design", test: /[\\/]node_modules[\\/]@ant-design[\\/]/, chunks: 'all', priority: 1, }, antd: { name: "antd", test: /[\\/]node_modules[\\/]antd[\\/]/, chunks: 'all', priority: 1, }, companyLib: { name: "companyLib", test: /[\\/]node_modules[\\/]@companyLib[\\/]/, chunks: 'all', priority: 1, }, vendor: { name: "node_vendors", test: /[\\/]node_modules[\\/]/, chunks: 'all', // 新增优先级配置,确保第三方依赖缓存组优先级低于业务相关缓存组 priority: -10 }, // 新增业务公共代码缓存组 commons: { // 不手动指定name,webpack会自动拼接引用该公共模块的chunk名生成文件名 name: false, // 匹配除node_modules外的业务代码,可根据你实际业务代码的根目录调整 test: /[\\/]app[\\/]/, // 至少被2个chunk引用才抽离 minChunks: 2, chunks: 'all', // 优先级低于已有特定缓存组,高于第三方依赖缓存组 priority: -1, // 允许复用已经被其他缓存组抽离的模块,避免重复打包 reuseExistingChunk: true } }, }
配置说明
- 新增的
commons缓存组会自动识别业务代码中被2个及以上chunk引用的公共模块,无需手动指定匹配规则 - 不写死
name字段的情况下,webpack会自动生成MassCommEmail~MassCommModule.[hash].js格式的文件名,完全符合你的需求 - 原有抽离utlis、antd、companyLib等独立chunk的逻辑完全不受影响,不需要修改之前的配置
- 重新构建后两个懒加载组件的chunk体积会对应减小,不再包含重复的Filter模块代码
内容的提问来源于stack exchange,提问作者Ramji
相关产品推荐
相关产品推荐

