【问题标题】:Access system variable (Environment Variable) while building Angular 2 application在构建 Angular 2 应用程序时访问系统变量(环境变量)
【发布时间】:2018-02-22 16:42:40
【问题描述】:

我需要使用一个系统变量来构建我的 Angular 应用程序。

系统变量

server_url = http://google.com

我的 Environment.ts 文件看起来像

export const environment = {
  production: false,
  serveUrl: 'http://someurl.com',
  mleServerUrl: 'http://someurl2.com',
  botServerUrl: 'http://someurl2.com',
  DEBUG_LOG: true,
  azureAD: true,
  mleEnvironment: 'dev',
  multtenant: true,
  e2eTest: false
};

在执行ng build 命令时,我需要将serveUrl 值替换为http://google.com

【问题讨论】:

  • 如果需要在构建时设置,只需创建一个 npm 脚本,在运行 ng build 之前检索环境变量并替换环境文件中的值即可?

标签: javascript angular


【解决方案1】:

您需要一个 environment.prod.ts(与 environment.ts 在同一文件夹中)与

export const environment = {
  production: true,
  serveUrl: 'http://google.com',
};

那么你必须做一个ng build --prod

https://github.com/angular/angular-cli/wiki/build

【讨论】:

  • 要求是在不同的机器上可以有N 不同的URL 数量。所以只需要访问系统变量。
  • 没有 N 个 URL,如果你这样做,你会得到在开发中等于“someurl.com”的serveUrl,在生产中等于“google.com”在你的代码中,你可以使用environment.serveUrl 访问它我不确定我是否理解您的问题,但我觉得这就是您想要做的。
  • 让我们再举一个三人 A、B、C 的例子,其中 A 喜欢使用 google.com,B 喜欢使用 yahoo.com,C 喜欢 bing.com。假设它们在名为 server_url 的系统变量中都有该 url。现在在这三台机器上构建 Angular 应用程序时,它将从这些机器中读取 server_url 并将该值放入 environment.ts 文件并使用它。
  • 这就像基于系统变量构建 Angular 应用程序一样。现在你完全可以假设系统变量会一直存在。
  • 浏览器无法读取系统变量,您必须在构建过程中进行设置。我不确定 angular-cli 是否可以做到这一点。看看stackoverflow.com/a/45889613/9136781也许,它可以帮助你。
【解决方案2】:

如果您想使用系统环境变量而不是标准的角度方法,这里有几个选项:

  1. 创建可通过 Angular 应用程序使用的 env 服务;利用可以在部署时修改的env.js 文件。 https://www.jvandemo.com/how-to-use-environment-variables-to-configure-your-angular-application-without-a-rebuild/

  2. 使用自定义 Angular 构建修改您的 webpack 进程,允许您在构建时读取系统环境变量https://blog.usejournal.com/system-environment-variables-in-angular-1f4a922c7b4c

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-07-29
    • 2015-08-20
    • 2015-09-16
    • 2021-11-01
    • 2021-01-09
    • 1970-01-01
    • 2014-11-06
    相关资源
    最近更新 更多