如何将 .env 文件中的变量传递给 angular6 environment.ts 文件 [英] How to pass variables in .env file to angular6 environment.ts file
问题描述
使用 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'.
我的要求是:
- 使用
docker-compose up
在 docker 容器中运行应用程序 - 在应用程序代码中,获取
.env
文件中定义的环境变量.
- run application in docker container using
docker-compose up
- 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屋!