简体   繁体   English

从 .env 设置 Angular 6 环境变量

[英]Set up Angular 6 environment variables from .env

There's an angular 6 project using environment variables from ./project/src/environments/environment.prod.ts有一个 angular 6 项目使用来自./project/src/environments/environment.prod.ts环境变量

export const environment = {
  production: true,
  testVar: 'gg',
};

The backend for this project also has env variables in a .env file, so a lot of variable duplicate angular env variables.这个项目的后端在.env文件中也有 env 变量,所以很多变量重复了 angular env 变量。 It would be nice to have something like有类似的东西会很好

export const environment = {
  production: true,
  testVar: process.env.TEST_VAR
};

, so I didn't have to duplicate variables. ,所以我不必复制变量。

ie IE

I'd like to parse variables from a .env file and assign their values to angular env variables during typescript compilation on the server.我想解析.env文件中的变量,并在服务器上的打字稿编译期间将它们的值分配给 angular env 变量。

How can this be done?如何才能做到这一点? Maybe with webpack?也许用webpack?

UPDATE更新

Some clarification.一些澄清。 My .env file contains no json.我的 .env 文件不包含 json。 It looks like this:它看起来像这样:

TEST_VAR=1

UPDATE更新

Since ng eject is not available for Angular 6 , I don't seem to be able to hack into webpack config.由于ng eject 不适用于 Angular 6 ,我似乎无法侵入 webpack 配置。 Looks like deadend here.这里好像死路一条。

ng eject弹出

Overview概述

Temporarily disabled.暂时禁用。

Ejects your app and output the proper webpack configuration and scripts.弹出您的应用程序并输出正确的 webpack 配置和脚本。

You can create a config file and populate in Run-time.您可以创建一个配置文件并在运行时填充。

1) create a File(app-config.json) in assets folder with your variables 1)使用您的变量在资产文件夹中创建一个文件(app-config.json)

{ "servicesUrl": "https://localhost:8080/api"}

2) create a service (AppConfigService ) to read the file. 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) Next we need to tell our application to execute the loadAppConfig() method of our service. 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) create a function called "appInitializerFn" to call our service in AppModule (app.module.ts) 4)创建一个名为“appInitializerFn”的函数来调用我们在AppModule中的服务(app.module.ts)

const appInitializerFn = (appConfig: AppConfigService) => {
    return () => {
        return appConfig.loadAppConfig();
    }
};

...

@NgModule({
    ...
})
export class AppModule {}

5) import environment and use it :example 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/');
    }
}

for more information please see: link更多信息请参见: 链接

This question becomes also more and more important, when we want to containerize angular applications.当我们想要容器化 Angular 应用程序时,这个问题也变得越来越重要。

My research lead me to an idea, where I have to write a little node.js or typescript program, using dotenv for reading .env file and create the environment.ts file at buildtime, before starting ng serve.我的研究使我想到了一个想法,我必须在开始 ng serve 之前编写一个小 node.js 或打字稿程序,使用 dotenv 读取 .env 文件并在构建时创建 environment.ts 文件。 You can create entries in the package.json like this:您可以像这样在 package.json 中创建条目:

...
"config": "ts-node set-env.ts",
"server": "npm run config && ng serve"
...

and run it with并运行它

npm run server

Here is a good explanation with an example typescript file: https://medium.com/@ferie/how-to-pass-environment-variables-at-building-time-in-an-angular-application-using-env-files-4ae1a80383c以下是一个带有示例打字稿文件的很好的解释: https : //medium.com/@ferie/how-to-pass-environment-variables-at-building-time-in-an-angular-application-using-env-文件-4ae1a80383c

If you want to use variables in build time you could use dotenv如果你想在构建时使用变量,你可以使用dotenv

As early as possible in your application, require and configure dotenv.尽早在您的应用程序中,要求并配置 dotenv。

require('dotenv').config()

Create a .env file in the root directory of your project.在项目的根目录中创建一个 .env 文件。 Add environment-specific variables on new lines in the form of NAME=VALUE.在新行中以 NAME=VALUE 的形式添加特定于环境的变量。 For example:例如:

DB_HOST=localhost
DB_USER=root
DB_PASS=s1mpl3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM