如何在index.html中为Angular 6使用环境变量

Sha*_*ppa 23 account-kit angular6

我正在使用angular6,在我的项目中我使用Facebook Account Toolkit进行移动验证.

我需要使用以下代码在index.html文件中初始化Account toolkit.

  AccountKit.init({
   appId:"XX",
   state:"xx",
   version:"v1.2",
   fbAppEventsEnabled:true,
   debug:true
 });
Run Code Online (Sandbox Code Playgroud)

问题是,appId状态的值根据环境(开发/测试/生产)而变化.

如何在index.html文件中使用环境变量.

如果有人有角度6的解决方案,请告诉我.

提前致谢.

Art*_*yuk 31

您应该创建index.html的副本并将其命名为index.someenv.html,而不是在环境配置设置文件替换中的angular.json中:

"fileReplacements": [
    {
        "replace": "src/index.html",
        "with": "src/index.someenv.html"
    }
]
Run Code Online (Sandbox Code Playgroud)

当你运行build时,angular cli将替换这些文件

  • @DejanBogatinovski 从 Angular 8 开始,您无法通过“fileReplacements”替换索引文件。您必须通过“index”属性指定您自己的索引文件。例如:`“index”:“src/index.someenv.html”`。 (6认同)
  • 我正在这样做,但由于某种原因它仍然复制原始的 index.html 文件。我使用以下命令来构建角度应用程序:`ng build --prod -c production --output-path dist`。您知道为什么它不会用index.prod.html 替换index.html 文件吗? (2认同)
  • @JosephHorsch 仅 index.html 的内容将被替换,而不是文件名。 (2认同)

jcr*_*oll 27

这个答案取代了Artyom对 Angular 8 及更高版本的回答。将以下内容添加到您的angular.json:

"production": {
  "index": {
    "input": "src/index.someenv.html",
    "output": "index.html"
  },
},
Run Code Online (Sandbox Code Playgroud)


44k*_*rma 6

对我来说,上面的答案在 Angular 10 上不起作用,所以我创建了不同的文件夹用于暂存、生产等,并放置了 CLI 根据构建环境使用的 index.html

{
  "projects": {
    "yourApp": {
      "projectType": "application",
      "root": "",
      "sourceRoot": "src",
      "prefix": "app",
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "index": "src/index.html",
          },
          "configurations": {
            "production": {
              "index": "src/production/index.html",
            }
          }
        }
      }
    }
  }
}     
Run Code Online (Sandbox Code Playgroud)


小智 5

在 main.ts 文件中,您可以使用document.write(environment.variable)它,它会在 index.html 中写入您想要的内容

(我使用它来让 Google Analytics 脚本采用动态跟踪 ID,无论它是处于开发模式还是生产模式,并且它在 Angular6 中运行良好)

  • 您好,您能否提供一个小示例来展示您如何设法更新 index.html 文件中的 Analytics 脚本跟踪 ID?非常感激 (6认同)

小智 5

此处为 document.write(environment.variable) 的示例:https : //github.com/angular/angular-cli/issues/4451#issuecomment-285026543

import { environment } from './environments/environment';

if (environment.production) {
  document.write('<script type="text/javascript">// ProductionAnalyticsCodeHere</script>');
} else if (environment.staging) {
  document.write('<script type="text/javascript">// StagingAnalyticsCodeHere</script>');
}
Run Code Online (Sandbox Code Playgroud)

  • 这个有点危险,因为如果在加载页面后调用“document.write”,它将替换*整个* HTML 文档。 (2认同)