ng6 多environment配置
angular.json 包含构建目标的生产配置中的 fileReplacements 配置项, 默认情况下,这看起来像:
"configurations": {
"production": {
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.prod.ts"
}
],
当使用生产配置(通过ng build --prod或 ng build --configuration=production)时
src/environments/environment.ts文件将被替换为src/environments/environment.prod.ts
这对于在创建新构建时使用不同的代码或变量很有用。默认情况下,构建中不会替换任何文件。
您可以根据需要添加其他配置。要添加暂存环境,请创建一个src/environments/environment.ts被调用的副本src/environments/environment.staging.ts,然后将staging配置添加到angular.json:
"configurations": {
"production": { ... },
"staging": {
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.staging.ts"
}
]
}
}
您也可以向此环境添加更多配置选项。您的构建支持的任何选项都可以在配置中覆盖。
要使用登台配置进行构建,请运行ng build --configuration=staging。
要使用登台配置进行服务,必须编辑serve目标以使用staging 构建配置:
"serve": {
"builder": "@angular-devkit/build-angular:dev-server",
"options": {
"browserTarget": "your-project-name:build"
},
"configurations": {
"production": {
"browserTarget": "your-project-name:build:production"
},
"staging": {
"browserTarget": "your-project-name:build:staging"
}
}
},
所以,现在的目录结构是这样的
└── src
└── app
├── app.component.html
└── app.component.ts
└── environments
├── environment.prod.ts
├── environment.staging.ts
└── environment.ts
在里面使用环境变量app.component.ts可能看起来像这样:
import { Component } from '@angular/core';
import { environment } from './../environments/environment';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor() {
console.log(environment.production); // Logs false for default environment
}
title = 'app works!';
}
这样,构建系统可以替换每个配置中的原始系统

浙公网安备 33010602011771号