【问题标题】:How to use environment variable in index.html for Angular 6如何在 Angular 6 的 index.html 中使用环境变量
【发布时间】:2018-08-28 05:13:22
【问题描述】:

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

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

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

问题是,appIdstate 的值会根据环境(开发/测试/生产)而变化。

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

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

提前致谢。

【问题讨论】:

    标签: angular6 account-kit


    【解决方案1】:

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

    "fileReplacements": [
        {
            "replace": "src/index.html",
            "with": "src/index.someenv.html"
        }
    ]
    

    Angular cli 将在您运行构建时替换这些文件

    【讨论】:

    • 我正在这样做,但由于某种原因,它仍然会复制原始 index.html 文件。我正在使用以下命令来构建 Angular 应用程序:ng build --prod -c production --output-path dist。你知道为什么它不会用 index.prod.html 替换 index.html 文件吗?
    • @DejanBogatinovski 你能展示你的生产配置吗? (在 angular.json 中)
    • @JosephHorsch 只会替换 index.html 的内容,而不是文件名。
    • @DejanBogatinovski 从 Angular 8 开始,您无法通过 "fileReplacements" 替换索引文件。您必须通过"index" 属性指定您自己的索引文件。例如:"index":"src/index.someenv.html".
    • 请参阅 my answer 了解 Angular 8 及更高版本
    【解决方案2】:

    对于 Angular 8 及更高版本,此答案取代 Artyom's answer。将以下内容添加到您的angular.json

    "production": {
      "index": {
        "input": "src/index.someenv.html",
        "output": "index.html"
      },
    },
    

    【讨论】:

    • 这在 CI 构建中也很棒。让 index.tokens.html 包含 MY_PLACEHOLDER。 index.html 包含本地开发的默认值,并且在您的产品构建之前的管道中,将 MY_PLACEHOLDER 替换为管道变量。这允许将环境 URL 等值存储在管道中,对它们的更改将是简单地为给定的提交重新运行管道以生成具有新 URL 的文件,而不需要通过代码更改来提升各种环境。
    【解决方案3】:

    此处是 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>');
    }
    

    【讨论】:

    • 这个有点危险,因为如果在页面加载后调用document.write 将替换整个 HTML 文档。
    【解决方案4】:

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

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

    【讨论】:

    • 您好,您能否提供一个小示例来说明您是如何设法更新 index.html 文件中的 Analytics 脚本跟踪 ID 的?非常感谢
    【解决方案5】:

    对我来说,上面的答案在 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",
                }
              }
            }
          }
        }
      }
    }     
    

    【讨论】:

      【解决方案6】:

      我认为你可以在 main.ts 中完成所有操作

      const env = environment;
      
       AccountKit.init({
         appId:env.appId,  // this lane
         state:env.state,  // this lane
         version:"v1.2",
         fbAppEventsEnabled:true,
         debug:true
      });
      

      谢谢。

      【讨论】:

      • 我在加载谷歌图表 js 并需要从环境变量中传递正确的 api 时遇到了类似的问题。将初始化调用移至 main.ts 对我有用。当然,在加载/初始化脚本时,时间问题始终是一个问题,因此请告诉我们它是否适用于您的场景。
      【解决方案7】:

      我在 main.ts 中添加了这个:

      var html = document.documentElement.innerHTML
      document.documentElement.innerHTML = html.replace("Replace me!", environment.variable)
      

      请注意,在最初加载页面时,旧值仍会存在于 index.html 中一段时间​​。 (例如,使用它来替换页面标题,您将看到在替换发生之前显示的旧值。)

      【讨论】:

      【解决方案8】:

      通过将 DOCUMENT 注入您的 AppComponent 来避免直接访问文档对象。

      import { DOCUMENT } from '@angular/common';
      ...
        public constructor(
          @Inject(DOCUMENT) private doc: any
        ) {
      

      在ngOnInit()中添加标签

      ngOnInit() {
          this.setYourScriptTag();
      }
      

      设置它的私有函数

        private setYourScriptTag() {
          const s = this.doc.createElement('script');
          s.type = 'text/javascript';
          s.innerHTML = `AccountKit.init({
         appId: "${environment.appId}",
         state: "${environment.state}",
         version:"v1.2",
         fbAppEventsEnabled:true,
         debug:true
       });`;
          const head = this.doc.getElementsByTagName('head')[0];
          head.appendChild(s);
        }
      

      这个答案来自edodosi

      https://github.com/angular/angular-cli/issues/4451#issuecomment-384992203

      【讨论】:

        【解决方案9】:

        将您的环境文件导入 .ts 文件。

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

        在您的类中创建必填字段,将 环境 中的值分配给构造函数中的这些变量,使用 .html 文件中的常规绑定。

        .ts

        import { Component } from '@angular/core';
        import { environment } from '../environments/environment';
        
        @Component({
          selector: 'app-root',
          templateUrl: './app.component.html',
          styleUrls: ['./app.component.css']
        })
        export class AppComponent {
          public production = true;
          constructor() {
            this.production = environment.production;
          }
        }
        

        .html

        <span>{{production}}</span>
        

        【讨论】:

        • 谢谢,Igor Litvinovich,但我想在 index.html 中使用该环境变量,而不是在 .ts 文件中使用该特定 html 文件,我使用的是 angular6。并且导入在 index.html 文件中不起作用。
        猜你喜欢
        • 2021-10-07
        • 2020-03-02
        • 1970-01-01
        • 2019-03-09
        • 2019-07-04
        • 2020-01-17
        • 2019-01-15
        • 1970-01-01
        • 2019-02-18
        相关资源
        最近更新 更多