如何在index.html中访问环境变量?

时间:2017-07-14 15:07:06

标签: angular angular-cli

我正在尝试实施Google Analytics。我的每个环境(dev,prod等)都有不同的跟踪代码。据我所知,我无法从std::thread访问environments.ts

我尝试从Angular内部加载脚本,但后来我忘记了应用程序初始加载的时间。我还看到index.html.angular-cli.json部分我可以使用,但我不知道如何根据环境切换我运行的脚本。

我该如何设置?

2 个答案:

答案 0 :(得分:1)

对于Angular 8或更高版本,只需修改 angular.json 中的 production:configuration 部分,如下所示

    "build": {
      "builder": "@angular-devkit/build-angular:browser",
      "options": {
        "index": "src/index.html"
      },
      "configurations": {
        "production": {
          "fileReplacements": [
            {
              "replace": "src/environments/environment.ts",
              "with": "src/environments/environment.prod.ts"
            }
          ],
          "index": "src/index.prod.html"
        }
      }
    }

希望这个答案有帮助。

关于, Kirti Singh | Soluzione IT服务

答案 1 :(得分:0)

从Angular 6开始,您可以在angular.json中配置文件替换:

"configurations": {
  "dev": {
    ...
    "fileReplacements": [
      {
        "replace": "src/myScripts.js",
        "with": "src/myScripts.dev.js",
      }
    ]
  },
  "production": {
    ...
    "fileReplacements": [
      {
        "replace": "src/myScripts.js",
        "with": "src/myScripts.prod.js",
      }
    ]
  }