如何根据环境替换Angular 8.3+中的index.html?

时间:2019-12-13 14:08:14

标签: angular webpack jhipster angular8

我正在使用使用jhipster,Spring Boot和Angular设置的应用程序

我需要为应用设置不同的公共密钥,具体取决于应用是在开发人员还是产品上运行。

我已经在我的angular.json中坐了很长时间了,并用谷歌搜索了一堆解决方案,尝试了所有基于angular.json的解决方案。

这是我在angular.json中尝试过的内容:

  • “索引”的旧用法
  • fileReplacements
  • 新索引“输入”“输出”选项
  • 对于后者,我已经遍历了将路径写入可能想到的索引文件的所有方法(仅包括文件名)。

我所有的三个索引文件都在webapp目录中。
angular.json (相关位):

  "root": "",
  "sourceRoot": "src/main/webapp",
  "projectType": "application",
  "architect": {
    "build": {
      "builder": "@angular-devkit/build-angular:browser",
      "options": {
        "index": "src/main/webapp/index.html",
        "configurations": {
          "production": {
            "index": {
              "input": "src/main/webapp/index-prod.html",
              "output": "src/main/webapp/index.html"
            }
          }
      },
        "scripts": [

        ],
        "styles": [
          "./src/main/webapp/teststyle.css"
        ]
      }
    }
  }

该项目没有environment.ts文件,但正在通过webpack magic调用enableProdMode()并按预期方式运行。

我该怎么办? 理想情况下,我们希望不必在环境之间进行重建,但是在这一点上,只要index.html文件自动更改,我就接受它。

3 个答案:

答案 0 :(得分:0)

您的fileReplacements文件中有angular.json个数组

"fileReplacements": [
   {
       "replace": "src/environments/environment.ts",
       "with": "src/environments/environment.prod.ts"
    },
    // belowe object is the example 
    {
       "replace": "src/index.html",  
       "with": "src/index-prod.html"  
    }
],

您需要将对象放入fileReplacements数组中应位于的位置

{
       "replace": "the file which should be replaced",
       "with": "the file which should replace {replace} file"
}

以及您何时成为

  1. 通过ng build --prodng serve --prod构建项目,它将与index-prod.html

  2. 一起编译项目
  3. 通过ng buildng serve构建项目,它将与index.html

  4. 一起编译项目

答案 1 :(得分:0)

configurations属性必须位于options正下方的build属性之外。

"architect": {
  "build": {
    "options": {
      "index": "src/index.html", // non production index
    },
    "configurations": {
      "production": {
        "index": { // production index replacement
          "input": "src/index.prod.html",
          "output": "index.html"
        }
      }
    }
  }
}

答案 2 :(得分:0)

除了@fridoo的答案。 Net Basal撰写了一篇精彩的文章,介绍了本例中的选项。

netbasal | environment-based-index-html-with-angular-cli