在Angular 5环境中使用process.env [英] Use process.env in Angular 5 environment
问题描述
我尝试使用标准的ng build --prod
命令构建Angular 5应用程序,并且我想将environment.prod.ts
中的基本API网址设置为取决于我的process.env
变量的值.
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.
这是我的文件
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'.
在构建应用程序时如何根据环境变量设置API网址?
How can I set my API-Url according to an env variable when building the application?
推荐答案
在Angular代码的编译时,您将无权访问process.env
.
You won't have access to process.env
at compile-time of the Angular code.
process.env
可用于Node
应用程序,而Angular应用程序不可用.
process.env
is available to Node
applications, which an Angular application is not.
您有几种选择:
1)如果确实需要动态更改环境文件,请在构建管道中执行某种任务以用正确的值更新环境文件.
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)只需对其进行硬编码并制作几个环境文件以匹配您的每个环境.您可以在angular-cli.json中指定您的环境.
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.
选项2听起来似乎很适合您.在这种情况下,您要将其放在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"
}
并使用ng build --env=prod
构建您的应用.
这里有更深入的信息: https://alligator.io/angular/environment-variables/
Here is more in-depth information: https://alligator.io/angular/environment-variables/
这篇关于在Angular 5环境中使用process.env的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!