angular - 如何在运行 ng-build 命令时动态更改 index.html 文件中的内容 [英] angular - How to dynamically change the content in the index.html file when running the ng-build command

查看:41
本文介绍了angular - 如何在运行 ng-build 命令时动态更改 index.html 文件中的内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在运行 ng build 命令时更改脚本标记的 URL 使用 --prod 选项不使用 --prod 选项.下面是一个例子.

I want to change the URL of a script tag when I'm running the ng build command with the --prod option and without the --prod option. Following is an example.

ng build --prod

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

ng build

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

我怎样才能做到这一点?

How can I achieve this?

推荐答案

对于从 v6.1.0-beta.2 开始的当前版本的 Angular,您可以使用 中的 fileReplacements 值angular.json 文件配置,详见本答案:https://stackoverflow.com/a/57274333/228429 来自 @massic80.

For current versions of Angular from v6.1.0-beta.2 on, you can use the fileReplacements value in the angular.json file configurations as detailed in this answer: https://stackoverflow.com/a/57274333/228429 by @massic80.

更多信息:https://github.com/angular/angular-cli/issues/4451#issuecomment-395651237

对于 v6.1.0-beta.2 之前的旧版本,Angular CLI 不提供任何此类功能.但是您可以使用环境变量在运行时动态注入适当的脚本.

For older versions before v6.1.0-beta.2, Angular CLI does not provide any such feature. But you can use environment variables to inject proper scripts dynamically on run time.

例如:

main.ts

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

if (env.production) {
   const script = document.createElement('script');
   script.src = https://my-site.net/prod.js
   document.head.appendChild(script);
} else {
   const script = document.createElement('script');
   script.src = https://my-site.net/dev.js
   document.head.appendChild(script);
}

在此处阅读更多信息:https://github.com/angular/angular-cli/issues/4451#issuecomment-285329985

这篇关于angular - 如何在运行 ng-build 命令时动态更改 index.html 文件中的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆