如何将.env文件中的变量传递到angular6 environment.ts文件 [英] How to pass variables in .env file to angular6 environment.ts file

查看:252
本文介绍了如何将.env文件中的变量传递到angular6 environment.ts文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于 angular6 ,全局变量 process 是未定义的。

With angular6, the global variable process is undefined.

我使用 docker-compose.yml Dockerfile

我创建 .env 文件存储我的 docker-compose.yml 使用的秘密变量

I create .env file store my secret variables used by docker-compose.yml

但是,如果我将变量保存在应用程序代码的 .env 文件中,如下所示:

But, if I get the variables stored in .env file in application code like this:

process.env.GITHUB_ACCESS_TOKEN

将引发错误

ERROR in src/app/app.module.ts(41,58): error TS2304: Cannot find name 'process'.
src/app/app.module.ts(53,12): error TS2304: Cannot find name 'process'.

我的要求是:


  1. 使用 docker-compose up

  2. 在Docker容器中运行应用程序,在应用程序代码中,获取定义的环境变量在 .env 文件中。

  1. run application in docker container using docker-compose up
  2. Within application code, get the environment variables which are defined in .env file.

这是我的 docker-compose.yml

version: '2.1'

services:
  angular-apollo-starter:
    image: angular-apollo-starter
    build: .
    environment:
      NODE_ENV: production
    env_file: .env
    ports:
      - 8080:80

我认为传递环境变量的工作流程应如下:

I think pass environment variables workflow should be like this:

.env -> environment.prod.ts -> 应用程序代码

更新

我发现了有关此问题的问题: https://github.com/angular/angular-cli/issues/4318

I found an issue about this problem: https://github.com/angular/angular-cli/issues/4318

推荐答案

您可以创建脚本并在使用 prebuild 之类的脚本执行该脚本之前执行该脚本。在该脚本中,您可以访问 process ,并且可以用所需的内容替换environment.ts中的某些值。

You can create a script and execute it before build with something like prebuild. In that script you have access to process and you can replace some values in environment.ts with what you need.

这篇关于如何将.env文件中的变量传递到angular6 environment.ts文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆