最近在升级公司的Angular项目,项目使用Angular-Cli搭建,UI使用Angular Metarial库和懒加载路由,Angular版本由v10升级到v13。 升级指导:https://update.angular.io/
问题:升级之后ng serve 编译非常慢
仅仅启动都要用到90s+ 开发过程中的重构时间也变长了,任何一个小的改动,哪怕仅仅是文字或者样式的改动都要重新编译,并且耗时10s+到40s不等 一顿操作猛如虎,一看战绩零杠五,这样肯定不行嘚,会大大降低开发的效率。谷歌一下才发现,确实有很多“升级到Angular12之后,ng serve 编译缓慢”之类的问题,大概能确认不是我单独项目的问题,嗯,下面就是寻找解决办法啦。
原因:
在Angular 12 版本中,运行ng build ,现在默认为生产模式。这是一个受欢迎的变化,因为这样可以减少不小心将一个开发构建部署到生产环境中的机会,后者要慢得多,规模也大得多,会让人觉得Angular很慢。这也与其他为生产而构建的web框架一致。
Angular服务于应用的方式,本质上是用监视模式进行构建。正如前面提到的,在默认情况下,在启用生产优化的情况下进行构建。这会增加构建过程的时间。
解决办法 有一个迁移来添加“development”构建配置。
要手动修复这个问题,您需要将开发选项添加为默认值,并将serve中target的defaultConfiguration 设置为development 。 示例:
{
"$schema": "./node_modules/@angular/cli/lib/config/schema.json",
"version": 1,
"newProjectRoot": "projects",
"projects": {
"ngv12": {
"projectType": "application",
"schematics": {},
"root": "",
"sourceRoot": "src",
"prefix": "app",
"architect": {
"build": {
"builder": "@angular-devkit/build-angular:browser",
"options": {
"outputPath": "dist/ngv12",
"index": "src/index.html",
"main": "src/main.ts",
"polyfills": "src/polyfills.ts",
"tsConfig": "tsconfig.app.json",
"assets": [
"src/favicon.ico",
"src/assets"
],
"styles": [
"src/styles.css"
],
"scripts": []
},
"configurations": {
+ "development": {
+ "vendorChunk": true,
+ "extractLicenses": false,
+ "buildOptimizer": false,
+ "sourceMap": true,
+ "optimization": false,
+ "namedChunks": true
+ },
"production": {
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.prod.ts"
}
],
"optimization": true,
"outputHashing": "all",
"sourceMap": false,
"namedChunks": false,
"extractLicenses": true,
"vendorChunk": false,
"buildOptimizer": true,
"budgets": [
{
"type": "initial",
"maximumWarning": "2mb",
"maximumError": "5mb"
},
{
"type": "anyComponentStyle",
"maximumWarning": "6kb",
"maximumError": "10kb"
}
]
}
},
+ "defaultConfiguration": "production"
},
"serve": {
"builder": "@angular-devkit/build-angular:dev-server",
+ "defaultConfiguration": "",
"options": {
+ "browserTarget": "ngv12:build:development"
},
"configurations": {
"production": {
"browserTarget": "ngv12:build:production"
}
}
}
}
}
},
"defaultProject": "ngv12"
}
效果:
再次运行可见速度快了很多,启动项目60s,重构时间也均未超过10s
参考资料
Speeding up the development serve after upgrading to Angular v12
|