升级Webpack 5后splitChunks配置异常,vendor缓存组失效如何解决?
Webpack 5 splitChunks vendor组失效问题解决
问题出在vendor组的正则匹配语法上,Webpack 5对正则解析更严格,原Webpack 4中使用的(!@common)写法并非标准正则负匹配语法,无法被正确识别。
要将@common目录以外的所有node_modules模块打包到vendor组,需要用标准正则负向先行断言改写test规则:
修正后的完整配置
splitChunks: { chunks: 'all', maxInitialRequests: Infinity, cacheGroups: { common: { test: /[\\/]node_modules[\\/](@common)[\\/]/, name: 'common', priority: 10, // 确保common组优先级高于vendor ...chunksGroupOptions }, vendor: { test: /[\\/]node_modules[\\/](?!@common)/, name: 'vendors', priority: 5, ...chunksGroupOptions } } }
关键说明
- 正则修正:
(?!@common)是标准正则负向先行断言,表示匹配node_modules/之后**不紧跟@common**的路径。 - 优先级设置:给common组设置更高的
priority值,确保@common模块会被优先分配到common组,避免被vendor组匹配。
内容的提问来源于stack exchange,提问作者Komakino_1251
相关产品推荐
相关产品推荐

