![](/img/trans.png)
[英]Is it possible to use environment variables from .env package in the npm scripts
[英]Set up Angular 6 environment variables from .env
有一個 angular 6 項目使用來自./project/src/environments/environment.prod.ts
環境變量
export const environment = {
production: true,
testVar: 'gg',
};
這個項目的后端在.env
文件中也有 env 變量,所以很多變量重復了 angular env 變量。 有類似的東西會很好
export const environment = {
production: true,
testVar: process.env.TEST_VAR
};
,所以我不必復制變量。
IE
我想解析.env
文件中的變量,並在服務器上的打字稿編譯期間將它們的值分配給 angular env 變量。
如何才能做到這一點? 也許用webpack?
更新
一些澄清。 我的 .env 文件不包含 json。 它看起來像這樣:
TEST_VAR=1
更新
由於ng eject 不適用於 Angular 6 ,我似乎無法侵入 webpack 配置。 這里好像死路一條。
彈出
概述
暫時禁用。
彈出您的應用程序並輸出正確的 webpack 配置和腳本。
您可以創建一個配置文件並在運行時填充。
1)使用您的變量在資產文件夾中創建一個文件(app-config.json)
{ "servicesUrl": "https://localhost:8080/api"}
2)創建一個服務(AppConfigService)來讀取文件。
@Injectable()
export class AppConfigService {
private appConfig;
constructor (private injector: Injector) { }
loadAppConfig() {
let http = this.injector.get(HttpClient);
return http.get('/assets/app-config.json')
.toPromise()
.then(data => {
this.appConfig = data;
})
}
get config() {
return this.appConfig;
}
3) 接下來我們需要告訴我們的應用程序執行我們服務的 loadAppConfig() 方法。
import { NgModule, APP_INITIALIZER } from '@angular/core';
import { AppConfigService } from './services/app-config.service';
@NgModule({
...,
providers: [
AppConfigService,
{
provide: APP_INITIALIZER,
useFactory: appInitializerFn,
multi: true,
deps: [AppConfigService]
}
],
...
})
export class AppModule { }
4)創建一個名為“appInitializerFn”的函數來調用我們在AppModule中的服務(app.module.ts)
const appInitializerFn = (appConfig: AppConfigService) => {
return () => {
return appConfig.loadAppConfig();
}
};
...
@NgModule({
...
})
export class AppModule {}
5)導入環境並使用它:示例
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { AppConfigService } from './services/app-config.service';
@Injectable()
export class DataContextService {
basePath: string;
constructor (private environment: AppConfigService, private http: HttpClient) {
this.basePath = environment.config.servicesBasePath;
}
getNames() {
return this.http.get(this.basePath + '/names/');
}
}
更多信息請參見: 鏈接
當我們想要容器化 Angular 應用程序時,這個問題也變得越來越重要。
我的研究使我想到了一個想法,我必須在開始 ng serve 之前編寫一個小 node.js 或打字稿程序,使用 dotenv 讀取 .env 文件並在構建時創建 environment.ts 文件。 您可以像這樣在 package.json 中創建條目:
...
"config": "ts-node set-env.ts",
"server": "npm run config && ng serve"
...
並運行它
npm run server
以下是一個帶有示例打字稿文件的很好的解釋: https : //medium.com/@ferie/how-to-pass-environment-variables-at-building-time-in-an-angular-application-using-env-文件-4ae1a80383c
如果你想在構建時使用變量,你可以使用dotenv
盡早在您的應用程序中,要求並配置 dotenv。
require('dotenv').config()
在項目的根目錄中創建一個 .env 文件。 在新行中以 NAME=VALUE 的形式添加特定於環境的變量。 例如:
DB_HOST=localhost
DB_USER=root
DB_PASS=s1mpl3
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.