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

22
我正在处理一个使用jhipster、Spring Boot和Angular设置的应用程序。
我需要根据应用程序是否在开发或生产环境下运行来设置不同的公钥。
我已经花了相当长的时间在我的angular.json上,并且浏览了很多解决方案,尝试了所有基于angular.json的方法。
以下是我在angular.json中尝试过的内容:
- 旧版“index”的使用 - fileReplacements - 新版本“input”“output”选项的使用 - 对于后者,我尝试使用可能想到的所有索引文件路径(包括仅文件名)。
我的三个索引文件都在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文件,但是enableProdMode()已被调用(通过webpack魔法),并且表现如预期。我该怎么办?理想情况下,我们希望不必在环境之间重新构建,但在这一点上,只要index.html文件自动更改,我就会接受它。

JHipster并不完全支持angular.json,无法确定您的更改是否已被考虑,特别是构建未由angular-cli处理。 - Gaël Marziou
那么我如何在我的技术堆栈中完成相同的事情呢? - Marvin Falkner
你看过 webpack/webpack.common.js 吗?它定义了一些常量,比如 DEBUG_INFO_ENABLED,然后在 Angular 文件中使用这些常量来根据你的应用程序是在开发环境还是生产环境下运行来修改某些行为。 - Gaël Marziou
2个回答

53

索引选项支持以下长格式:

"index": {
  "input": "src/index.html", // used index file from your project folder
  "output": "index.html", // created index file in your outputPath
},

angular.json 的示例:

"architect": {
  "build": {
    "options": {
      "outputPath": "dist/myproject",
      "index": "src/index.html", // default index file (shorthand form)
    },
    "configurations": {
      "production": {
        "index": { // production index replacement (longhand form)
          // use the file at 'src/index.prod.html' in production builds
          "input": "src/index.prod.html",
          // create the index file under 'index.html' in your outputPath
          "output": "index.html"
        }
      }
    }
  }
}

此功能已添加于Angular Cli v8.2.0-next.0中。

相关GitHub问题:https://github.com/angular/angular-cli/issues/14599


1
不知道有一个单独的index文件替换部分,一直在使用fileReplacements,但根本没有起作用。 - Shaharyar

3

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接