Angular 5 - 动态基础引用导致重复加载 bundles|chunks

Angular 5 - Dynamic base reference is causing duplicate loading of bundles|chunks

我在项目中使用Angular 5.2 版本。我在 index.html 中动态设置基本引用以满足不同客户端的不同 URL。

应用程序主页 url 如下所示:-

http://example.com/client1/app/login
http://example.com/client2/app/login
http://example.com/client3/app/login

client1、client2等是IIS中的虚拟目录

当我 运行 浏览器中的应用程序时,我可以从检查中看到 window 正在加载重复的块并导致应用程序页面变慢。

有一件事我观察到重复块的 Web 请求 url。比方说 script.xxxxxxxxxxxxxxxxxxxxxx.bundles.css。

第一个网络请求:- https://example.com/client1/scripts.7186135389ca4b63fab4.bundle.js

第二次网络请求(重复):-https://example.com/scripts.7186135389ca4b63fab4.bundle.js

不需要第二个网络请求。而且我无法判断它是如何出现的。

Index.html 在我的项目中看起来像这样 :-

<!doctype html>
<html lang="en">

    <head>
        <meta charset="utf-8">
        <title>Web</title>
        <link href="/assets/Images/favicon.ico" rel="shortcut icon" type="image/x-icon">
        <base id="baseHref" href="/">
        <script>
            (function () {
                if (window.location.hostname !== 'localhost') document.getElementById('baseHref').href = "/" + window.location.pathname.split('/')[1] + "/";
            })();
        </script>
        <meta name="viewport" content="width=device-width, initial-scale=1">
    </head>
    <body>
      <app-root></app-root>
    </body>
    </html>

请建议如何解决此问题。

不使用 HTML 属性,而是使用 the APP_BASE_HREF provider。您可以使用动态工厂来获得随时间变化的值。

您可以使用 ng build --base-href /myUrl/.

或在您的 angular.json 中添加 "baseHref" : "MY_APP_BASE_HREF_2"

相关 post 更多信息:

Add this to head section in index.html

<base href="/">
 <script>
 (function() {
  window['_app_base'] = '/' + window.location.pathname.split('/')[1];
 })();
</script>

Then in the app.module.ts file, add { provide: APP_BASE_HREF, useValue: window['_app_base'] || '/' } to the list of providers, like so:

import { NgModule, enableProdMode, provide } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { APP_BASE_HREF, Location } from '@angular/common';
import { AppComponent, routing, appRoutingProviders, environment } from './';
 if (environment.production) {
 enableProdMode();
}

  @NgModule({
  declarations: [AppComponent],
   imports: [
   BrowserModule,
   HttpModule,
   routing],
   bootstrap: [AppComponent],
   providers: [
   appRoutingProviders,
   { provide: APP_BASE_HREF, useValue: window['_app_base'] || '/' },
 ]
})
export class AppModule { }

问题出在 ng 构建参数期间。

之前是

ng build --prod -e=dev --base-href=/Client1

在我将结尾 / 添加到 ng build 语句后,它工作正常。

ng build --prod -e=dev --base-href=/Client1/

重复的 angular 块消失了。