如何在 Angular 7 中设置静态文件的基本路径?

How to set base path for static files in Angular 7?

我已经尝试了三种方法。

第 1 名:index.html

<base href="/customer">

第二名:app.module.ts

@NgModule({
  providers: [{provide: APP_BASE_HREF, useValue: '/customer'}]
})

第 3 次:app-routing.module.ts

const routes: Routes = [
  { path: "", redirectTo: "/customer", pathMatch: "full" },
  {
    path: "customer",
    component: CustomerComponent,
    data: { animation: "HomePage" }
  }
];

上述所有方法都适用于 URL 路由,我得到了想要的 URL。

http://localhost:4200/customer

但是,静态文件(js 和图像)仍在加载基本路径 'http://localhost:4200/'. I need it to have like http://localhost:4200/customer/main.js

因此,出于某些安全验证的原因,我正在尝试 http://localhost:4200/customer/main.js instead of http://localhost:4200/main.js

同样可以在下面的截图中看到。

您可以将 --baseHref 命令行标志与 ng serveng build 一起使用,这意味着您不再需要为 app-routing.module.ts[=16= 中的路由添加前缀]

ng serve --baseHref=/customer/

使用

构建
ng build --baseHref=/customer/

我从 angular 5 迁移到 7 时遇到了完全相同的错误。这可能与 angular 附加构建 js 文件的方式有关。如果您已经将 <base href="/"> 添加到 index.html 但脚本仍在从相对路径加载,则可能是因为没有 <body> 标记。尝试将 <body> 标记添加到 index.html 文件中,看看它是否有效。

您可以在 ng build 命令中使用 --deploy-url 参数。

示例:ng build --deploy-url /my/assets

有关 https://angular.io/guide/deployment 的更多详细信息。