在angular程序开发的时候,我们一般会使用三种环境,比如:开发环境、测试环境、生产环境。针对不同的环境使用不同的代码,比如接口地址。
开发环境:environment.ts——用于程序开发 (创建项目时自动生成)
export const environment = {
production: false,
baseUrl: '开发环境url'
};
测试环境:environment.test.ts——用于程序完成,测试产品 (手动创建)
export const environment = {
production: true,
baseUrl: '测试环境url'
};
生产环境:environment.prod.ts——测试完成,可对外开发 (创建项目时自动生成)
export const environment = {
production: true,
baseUrl: '生产环境url'
};
比如添加测试(test)环境文件:
首先在angular.json文件中复制production部分代码,然后放在当前代码的后面,将production
更改为test
, 文件引用更改为environment.test.ts
"production": {
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.prod.ts"
}
],
"optimization": true,
"outputHashing": "all",
"sourceMap": false,
"extractCss": true,
"namedChunks": false,
"aot": true,
"extractLicenses": true,
"vendorChunk": false,
"buildOptimizer": true,
"budgets": [
{
"type": "initial",
"maximumWarning": "2mb",
"maximumError": "5mb"
}
]
},
复制更改后的代码为:
"test": {
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.test.ts"
}
],
"optimization": true,
"outputHashing": "all",
"sourceMap": false,
"extractCss": true,
"namedChunks": false,
"aot": true,
"extractLicenses": true,
"vendorChunk": false,
"buildOptimizer": true,
"budgets": [
{
"type": "initial",
"maximumWarning": "2mb",
"maximumError": "5mb"
}
]
}
http.service.ts
import { environment } from '../../environments/environment';
console.log(environment.baseUrl);
// 默认使用的就是environment.prod.ts
ng build
ng build --configuration=test
ng serve // 直接启动默认就是生产环境
--prod : 压缩构建文件
ng build --prod