How to pass variables in .env file to angular6 env

2019-08-21 14:18发布

With angular6, the global variable process is undefined.

I dockerlize my angular app using docker-compose.yml and Dockerfile

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

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

process.env.GITHUB_ACCESS_TOKEN

An error will be thrown

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'.

My requirements are:

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

Here is my 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 -> application code

update

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

1条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-08-21 14:59

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.

查看更多
登录 后发表回答