【问题标题】:How to set base path for static files in Angular 7?如何在 Angular 7 中设置静态文件的基本路径?
【发布时间】:2019-10-26 17:13:54
【问题描述】:

我尝试了三种方法。

第一个:index.html

<base href="/customer">

第二个:app.module.ts

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

第三个: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/”加载。我需要它像http://localhost:4200/customer/main.js

因此,出于某些安全验证原因,我尝试将其设为 http://localhost:4200/customer/main.js 而不是 http://localhost:4200/main.js

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

【问题讨论】:

    标签: angular angular7 angular-routing angular7-router


    【解决方案1】:

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

    ng serve --baseHref=/customer/
    

    构建
    ng build --baseHref=/customer/
    

    【讨论】:

    • 由于“localhost:4200/customer/runtime.js”,应用程序加载失败。它不是路由,而是设置相对路径。
    • ng serve --baseHref=/customer/
    • 在设置“你的第一个应用程序”angular 7 项目时为我工作,然后使用ng serve --baseHref=/customer/。 url localhost:4200/customer 没有任何错误
    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

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

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

      更多详情请关注https://angular.io/guide/deployment

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-04-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-03-24
        • 2018-06-02
        相关资源
        最近更新 更多