一.创建环境变量文件:默认在app\environments\下有2个文件:environment.ts, environment.prod.ts ;
默认的开发环境是用environment.ts 这个文件;
我们也可以在该目录下创建其他的环境配置文件如:environment.dev.ts;
export const environment = {
production: false,
baseUrl: 'http://dev.test.com'
};
environment.prod.ts:
export const environment = {
production: false,
baseUrl: 'http://prod.test.com'
};
然后在angular.json 里面,对象路径为: projects -》工程名-》architect -》configurations -》修改为
"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"
}
]
},
"dev": {
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.dev.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"
}
]
}
}
},
二.环境变量的使用:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { environment } from '../../environments/environment'
@Injectable({
providedIn: 'root'
})
export class HomeService {
baseUrl = environment.baseUrl;
constructor() {
console.log(baseUrl);
}
}
三.文件的打包:执行命令:
ng build --prod --configuration=production 或者
ng build --prod --configuration=dev
或者修改package.json 为:
"scripts": {
"ng": "ng",
"start": "ng serve --host 192.168.1.8 --open",
"build": "ng build --prod --configuration=production",
"buildDev": "ng build --prod --configuration=dev",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e"
},
自动根据环境的变量,得到对应的变量值