Angular8项目如何将自动生成的Vendor.js中node_modules依赖拆分为独立chunk
Angular 8 拆分Vendor.js独立分包方案
Angular 8 底层基于Webpack实现打包,你可以通过配置Webpack的代码分割规则,将指定第三方依赖从主Vendor.js中拆分出来生成独立分包,有两种常用实现方案:
方案一:使用Angular原生配置实现(无需额外安装依赖)
直接修改项目根目录下的angular.json配置即可实现拆分,找到对应项目的build配置节点,参考如下示例修改:
{ "projects": { "你的项目名称": { "architect": { "build": { "builder": "@angular-devkit/build-angular:browser", "options": { // 保留其他原有配置不变 "vendorChunk": true, "commonChunk": true }, "configurations": { "production": { // 保留其他原有生产环境配置不变 "optimization": { "scripts": true, "styles": true, "splitChunks": { "chunks": "all", "cacheGroups": { "lodash": { "test": /[\\/]node_modules[\\/]lodash[\\/]/, "name": "lodash", "priority": 40, "chunks": "all", "enforce": true }, "hammer": { "test": /[\\/]node_modules[\\/]hammerjs[\\/]/, "name": "hammer", "priority": 30, "chunks": "all", "enforce": true }, "graphql": { "test": /[\\/]node_modules[\\/]graphql[\\/]/, "name": "graphql", "priority": 20, "chunks": "all", "enforce": true }, "vendors": { "test": /[\\/]node_modules[\\/]/, "name": "vendors", "priority": 10, "chunks": "initial", "enforce": true } } } } } } } } } } }
参数说明:
test:用正则匹配对应依赖在node_modules中的存储路径,[\\/]是为了兼容Windows、Mac/Linux系统的路径分隔符name:拆分后生成的分包文件名前缀,打包时会自动追加哈希值,例如生成lodash.8a2d6f.jspriority:匹配优先级,数值越高越先匹配,避免指定依赖被打包进主Vendor包enforce: true:强制生成对应分包,忽略体积阈值限制
方案二:使用自定义Webpack配置实现(更灵活)
如果需要更复杂的拆分规则,可以通过自定义Webpack配置实现,步骤如下:
- 安装适配Angular 8版本的自定义构建器依赖:
npm install @angular-builders/custom-webpack@8 @angular-builders/dev-server@8 -D
- 修改
angular.json中的build配置,替换构建器并指定自定义配置文件路径:
{ "build": { "builder": "@angular-builders/custom-webpack:browser", "options": { // 保留其他原有配置不变 "customWebpackConfig": { "path": "./custom-webpack.config.js" } } } }
- 项目根目录新建
custom-webpack.config.js文件,编写拆分规则:
module.exports = { optimization: { splitChunks: { chunks: 'all', cacheGroups: { lodash: { test: /[\\/]node_modules[\\/]lodash[\\/]/, name: 'lodash', priority: 40, chunks: 'all', enforce: true }, // 其他需要拆分的依赖规则参照上面格式添加 vendors: { test: /[\\/]node_modules[\\/]/, name: 'vendors', priority: 10, chunks: 'initial', enforce: true } } } } }
注意事项
- 拆分完成后Angular会自动在打包后的
index.html中引入所有生成的分包,不需要手动处理 - 不建议拆分过多体积很小的依赖,避免增加页面请求数,优先拆分体积大、版本稳定长期不更新的第三方依赖
- 配置完成后执行
ng build --prod,查看dist目录即可确认对应分包文件是否生成
内容的提问来源于stack exchange,提问作者Mr Sumo
相关产品推荐
相关产品推荐

