Use process.env in Angular 5 environment

巧了我就是萌 提交于 2019-11-27 03:12:20

问题


I try to build an Angular 5 application with the standard ng build --prod command, and I want to set the basic API-Url in the environment.prod.ts to a value dependent on my process.env variables.

This is my file:

export const environment = {
    production: true,
    apiUrl: `${process.env.BASE_URL}` || 'http://localhost:8070/',
};

But when I try to build the application the following error occurs:

ERROR in src/environments/environment.ts(7,16): error TS2304: Cannot find name 'process'.

How can I set my API-Url according to an env variable when building the application?


回答1:


You won't have access to process.env at compile-time of the Angular code.

process.env is available to Node applications, which an Angular application is not.

You have several options:

1) Make a task of some sort in your build pipeline to update the environment file with the correct value if it truly needs to be dynamic.

2) Just hardcode it and make several environmental files to match each of your environments. You can specify your environments in your angular-cli.json.

Option number 2 sounds like it might be right for you. In that case, you want to put this in your angular-cli.json:

"environments": {
    "dev": "path/to/dev/env",
    "prod": "path/to/prod/env"
}

and build your app with ng build --env=prod.

Here is more in-depth information: https://alligator.io/angular/environment-variables/



来源:https://stackoverflow.com/questions/49496438/use-process-env-in-angular-5-environment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!