如何将 Angular 静态资产指向 WWW URL

How to point Angular static assets to WWW URL

当我 运行 ng build 我得到这个 index.html 文件:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>ApiApp</title>
  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>

<script type="text/javascript">
  const appData = JSON.parse('<%=json%>');
</script>

<app-root></app-root>
<script type="text/javascript" src="runtime.js"></script>
<script type="text/javascript" src="polyfills.js"></script>
<script type="text/javascript" src="styles.js"></script>
<script type="text/javascript" src="vendor.js"></script>
<script type="text/javascript" src="main.js"></script>
</body>
</html>

在构建后使用脚本我会将静态资产推送到某个 CDN,所以我实际上想生成一个 .html 文件,如下所示:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>ApiApp</title>
  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>

<script type="text/javascript">
  const appData = JSON.parse('<%=json%>');
</script>

<app-root></app-root>
<script type="text/javascript" src="http://cdn.github.com/runtime.js"></script>
<script type="text/javascript" src="http://cdn.github.com/polyfills.js"></script>
<script type="text/javascript" src="http://cdn.github.com/styles.js"></script>
<script type="text/javascript" src="http://cdn.github.com/vendor.js"></script>
<script type="text/javascript" src="http://cdn.github.com/main.js"></script>
</body>
</html>

(我编的域名cdn.github.com)。所以我可以手动为这些文件生成 url,但我想知道 Angular 是否允许我们以某种方式配置它?

您可以在 angular 项目的 angular.json 文件中配置它。

{
  "projects": {
    "<Your Angular Project Name>": {
        "architect": {
            "build": {
                "options": {
                    "baseHref": "/testapp/",
                    "deployUrl": "/testapp/",
                    ...
                }
            }
        }
    }
  }
}

deployUrl 基本上就是您要查找的内容。

关于可用的构建选项及其描述,您可以参考下面link: https://github.com/angular/angular-cli/wiki/build