Angular如何配置多套环境

1. 前言

在 Angular 应用程序中,默认情况下构建了两个环境文件 dev 和 prod。基于目标环境,您的应用程序可能具有不同的设置。您可以根据需要配置多个自定义环境。在这里,您将看到如何配置多个环境,如 staging、beta、QA、prod 等

2. 创建不同的环境文件

我们需要根据需要创建多个环境文件。这里我创建了两个文件:

  1. environment.stagging.ts
  2. environment.beta.ts

您可以使用 environment.prod.ts file 复制、粘贴和重命名(例如:environment.staging.ts),并根据需要设置环境变量值。

3. 修改 angular.json 文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
"projectName": {
...
"architect": {
"build": {
...
"configurations": {
"production": {
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.prod.ts"
}
]
},
"stagging": {
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.stagging.ts"
}
],
...
},
"beta": {
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.beta.ts"
}
],
...
}
}
...
}
...
}
...
}

修改 serve 配置, 以支持多环境

1
2
3
4
5
6
7
8
9
10
11
"configurations": {
"production": {
"browserTarget": "projectName:build:production"
},
"stagging": {
"browserTarget": "projectName:build:stagging"
},
"beta": {
"browserTarget": "projectName:build:beta"
}
}

修改 e2e 配置, 以支持多环境

1
2
3
4
5
6
7
8
9
"production": {
"devServerTarget": "projectName:serve:production"
},
"stagging": {
"devServerTarget": "projectName:serve:stagging"
},
"beta": {
"devServerTarget": "projectName:serve:beta"
}

4. 启动新环境

1
2
3
4
5
6

ng serve
ng serve –configuration=stagging
ng serve –configuration=beta
ng serve –prod

5. 编译新环境

1
2
3
4
5
6

ng build
ng build –configuration=stagging
ng build –configuration=beta
ng build –prod

6. Angular 系列文章

最新更新以及更多 Angular 相关文章请访问 Angular 合集 | 鹏叔的技术博客

7. 总结

在本篇文章中我们讲了如何配置新环境, 以及如何编译运行新环境. 希望对你有帮助!

8. 參考文檔

How To Configure Multiple Environments In Angular

作者

鹏叔

发布于

2022-04-03

更新于

2024-08-06

许可协议

评论