在 Angular 5 环境中使用 process.env [英] Use process.env in Angular 5 environment
问题描述
我尝试使用标准的 ng build --prod
命令构建一个 Angular 5 应用程序,并且我想在 environment.prod.ts
中设置基本的 API-Urlcode> 到依赖于我的 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:
src/environments/environment.ts(7,16) 中的错误:错误 TS2304:找不到名称进程".
如何在构建应用程序时根据环境变量设置我的 API-Url?
How can I set my API-Url according to an env variable when building the application?
推荐答案
更新
根据下面的评论,原始答案并不完全清楚——Angular 是用 Angular CLI 构建的,它是一个节点应用程序,但您无法直接从内部访问 process.env
在构建过程中的应用程序,因为它没有作为 Node 应用程序处理.
Per the comments below the original answer was not entirely clear -- Angular is built with Angular CLI, which is a node application, but you aren't able to access process.env
directly from within the app during that build process, as it's not processed as a Node application.
概念几乎保持不变,但理解上述内容很重要.
The concepts stay pretty much the same, but it's important to understand the above.
原创
您将无法在 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.
您有多种选择:
在构建管道中执行某种任务,以在环境文件确实需要动态时使用正确的值更新环境文件.
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.
只需对其进行硬编码并制作多个环境文件以匹配您的每个环境.您可以在 angular-cli.json 中指定您的环境.
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
构建您的应用.
and build your app with ng build --env=prod
.
这里有更深入的信息:https://alligator.io/angular/environment-variables/
这篇关于在 Angular 5 环境中使用 process.env的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!