Angular 2+, How to read environment variable in module (webpack)
我不知道如何读取环境变量。 我要在app.module.browser.ts中初始化我的APP_INITIALIZER,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | @NgModule({ bootstrap: [AppComponent], imports: [ BrowserModule, AppModuleShared, AppAuthModule ], declarations: [], providers: [ { provide: 'BASE_URL', useFactory: getBaseUrl }, { provide: APP_INITIALIZER, // <-- HERE useFactory: configurationServiceFactory, deps: [ConfigurationService], multi: true }, { provide: HTTP_INTERCEPTORS, useClass: TokenInterceptor, //AuthInterceptor, multi: true } ConfigurationService, ErrorLogService ] |
初始化之后,我有了一些常量变量。 我想阅读我的环境变量。 因此,我可以将其置于条件中,然后根据我的条件来导入模块。
1 2 3 4 5 6 7 8 9 10 11 | import { AccountsComponent } from"./customerList/components/accounts/accounts.component"; import { AccountsPlusComponent } from"./customerList/components/accounts-plus/accounts-plus.component"; let accountsInjection: any = ENV_VARIABLE ? AccountsComponent : AccountsPlusComponent; @NgModule({ declarations: [ accountsInjection ], imports: [ ... |
注意:我的项目中没有app / environments /文件夹...(我仍在寻找一种放置方法)
编辑:我也想提供更多信息,我正在使用WEBPACK,是否应该使用另一种方法来获取我的Envarionment变量?
In the case if you want to access variable as env.variable_name
Dotenv是加载环境变量的零依赖模块。
安装:
1 | npm install dotenv |
在项目的根目录中创建一个
1 2 | apiUrl= 'url' enviorement= 'dev' |
在组件中
1 | require('dotenv').config() |
将变量用作:
1 | process.env.appUrl, |
这是针对角度6的。但是在角度> 2的情况下,我们也可以具有类似的配置。
Angular.json
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | "configurations": { "dev": { "fileReplacements": [ { "replace":"src/environments/environment.ts", "with":"src/environments/environment.dev.ts" } ] }, "test": { "fileReplacements": [ { "replace":"src/environments/environment.ts", "with":"src/environments/environment.qa.ts" } ] } |
对于其他环境类似。
Package.json-
1 2 3 | "start":"ng serve --configuration=dev", "prod":"ng serve --configuration=prod", "test":"ng serve --configuration=test", |
在组件中-
1 2 3 4 5 | import { environment } from '/../environments/environment'; // as per your path //use like environment.property_name |