Nrwl/NX工作区中lib差异化配置
基于environment在业务代码中实现不同环境下的差异化配置
新增多环境environment
1、新增特定环境配置
# 如 environment.staging.ts
export const environment = {
production: true,
staging: true,
apiUrl: 'http://my-prod-url'
};
2、在angular.json 中添加 staging 环境配置
"configurations": {
"production": { ... },
"staging": {
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.staging.ts"
}
]
}
}
3. 基于staging的构建
ng build --configuration=staging
基于InjectionToken的DI(依赖注入)
1、在lib中创建目录app-config及index.ts
// index.ts 声明InjectionToken
import { InjectionToken } from '@angular/core';
export const APP_CONFIG = new InjectionToken('Application config');
2、修改tsconfig.json添加导出路径
"paths": {
"@app-workspace/app-config": ["libs/app-config/index.ts"]
}
3、app.module.ts中providers注入
import { APP_CONFIG } from '@app-workspace/app-config';
import { environment } from '../environments/environment';
@NgModule({
declarations: [AppComponent],
imports: [
BrowserModule,
AppRoutingModule,
],
providers: [
{ provide: APP_CONFIG, useValue: environment}
],
bootstrap: [AppComponent]
})
export class AppModule {}
4、lib中使用
import { APP_CONFIG } from '@app-workspace/app-config';
import { Inject, Injectable } from '@angular/core';
@Injectable()
export class AuthService {
constructor(
@Inject(APP_CONFIG) private appConfig: any
) {
console.log(this.appConfig.apiUrl);
}
}