Angular CLI - ng 服务 --serve-path

Nis*_*hah 5 angular-cli

我正在尝试使用 --serve-path 在该路径下为我的整个应用程序提供服务。例如,我希望我的路径是localhost:4200/foobar我使用的ng serve --serve-path=/foobar/。然后,当我转到该网址时,我的应用程序不会加载,并且出现空白屏幕。

Iva*_*sky 9

除了--serve-path选项之外,您还需要指定--base-href--deploy-url选项,否则您的资产将具有无效的源 URI。没有它们,您的index.html文件包含类似的内容

<head>
  <base href="/">
  ...
</head>
<body>
  ...
  <script src="vendor.js" defer></script>
  <script src="main.js" defer></script>
</body>
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,所有资产都有不正确的 URI /vendor.js/main.js而不是正确的 URI /foobar/vendor.js/foobar/main.js等等。

如果你使用ng serve --serve-path=/foobar/ --base-href=/foobar/,那就index.html看起来像

<head>
  <base href="/foobar/">
  ...
</head>
<body>
  ...
  <script src="vendor.js" defer></script>
  <script src="main.js" defer></script>
</body>
Run Code Online (Sandbox Code Playgroud)

如果你使用ng serve --serve-path=/foobar/ --deploy-url=/foobar/,同样index.html会看起来像

<head>
  <base href="/">
  ...
</head>
<body>
  ...
  <script src="/foobar/vendor.js" defer></script>
  <script src="/foobar/main.js" defer></script>
</body>
Run Code Online (Sandbox Code Playgroud)

这两个选项在现代 Angular 版本中都被视为已弃用(但仍适用于当前的 Angular CLI 12),建议在angular.json配置文件中使用构建器配置选项:

      ...
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "baseHref": "/foobar/",
            ...
Run Code Online (Sandbox Code Playgroud)

Angular 文档表示,使用baseHref通常是比deployUrl.