angular - 如何在运行 ng-build 命令时动态更改 index.html 文件中的内容

标签 angular angular-cli

我想在运行 ng build 命令时更改脚本标记的 URL 带有 --prod 选项并且没有 --生产选项。下面是一个例子。

ng build --prod

<!DOCTYPE html>
<html>
<head>
    <title>Home Page</title>
</head>
<body>
    <script src="https://my-site.net/prod.js"></script>
</body>
</html>

构建

<!DOCTYPE html>
<html>
<head>
    <title>Home Page</title>
</head>
<body>
    <script src="https://my-site.net/dev.js"></script>
</body>
</html>

我怎样才能做到这一点?

最佳答案

angular.json 中,您可以配置要使用的索引文件(我使用的是 Angular 8):

"projects": {
    "projectName": {
        "architect": {
            "build": {
                "options": {
                    "index": "src/index.html", // this is the default location (also for ng serve)
                    "configurations": {
                        "production": {
                            "index": "index-prod.html" // this is the prod version (you can also link it to /prod/index.html or whatever: it will be placed in the dist root folder with the provided name)
                        },
                        "development": {
                            "index": "index-whatever.html" // this is the version for ng build --configuration=development`
                        }
                    }
                }
            }/*, UPDATED: THIS DOESN'T WORK
            "serve": {
                "index": "dev/index.html" // file to be used in ng serve
            }*/
        }
    }
}

据我所知,除了第一个

之外,这些“索引”都不是强制性的

旁注:这是我刚刚通过一些尝试、构建和 ng serve 尝试的结果。我没有在任何文档中找到它。

检查一下并告诉我。

===========

2019 年 10 月 19 日更新: 我注意到上面报告的配置仍然使用 src/index.html 也用于 "@angular/cli": "^8.3.6", "上的 serve @angular/compiler-cli": "^8.2.8"。看起来 serve 本身没有覆盖。 我的问题是:serve 应该始终继承基础 index 配置吗?

尝试深入挖掘,我发现了这个:https://github.com/angular/angular-cli/issues/14599

有一个示例说明它应该如何与新的 CLI 一起工作,但试图替换

"development": {
    index": "index-whatever.html"
}

有一个

"development": {
    index": {
        "input": "index-whatever.html"
    }
}

和建筑,它给了我一个 架构验证失败,出现以下错误:数据路径“.index”应为字符串。

===========

20 年 4 月 10 日更新:

我刚刚注意到,在 10 月的更新中,我遗漏了最新代码片段中的引述。我不记得它是否是直接从我的代码中复制的——因此报告的错误可能与此有关——或者是我试图重写代码时输入错误。有时间我再看看

关于angular - 如何在运行 ng-build 命令时动态更改 index.html 文件中的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50113794/

相关文章:

angular - 将 Angular 项目移动到另一个文件夹给了我错误

javascript - 除了 Angular-Material md-checkboxes 之外,默认的浏览器复选框也出现了

linux - 无法在 ubuntu 上安装 Angular Cli

Angular 5 Promise 返回未定义

javascript - 如何将提交数据推送到现有的本地 json 文件中?

angular - Angular CLI 7.2.1 ng 新失败

angular - 在环境中配置 Angular 路由

Angular + Electron - 应用程序在刷新或更改时中断

angular - Angular DOM 中的 StaticInjectorError

javascript - 如何使用多嵌套 json 值修补响应式(Reactive)表单