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

Ashwini Verma picture Ashwini Verma · Jun 12, 2019 · Viewed 8.5k times · Source

I have tried three approaches.

1st : index.html

<base href="/customer">

2nd : app.module.ts

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

3rd : app-routing.module.ts

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

All the above approaches work well for URL routing and I get desired URL.

http://localhost:4200/customer

However, static files(js & images) are still loading with the base path 'http://localhost:4200/'. I need it to have like http://localhost:4200/customer/main.js.

Hence, I am trying to make it http://localhost:4200/customer/main.js instead of http://localhost:4200/main.js for some secure validation reason.

Same can be seen in below screenshot.

enter image description here

Answer

Avin Kavish picture Avin Kavish · Jun 12, 2019

You can use the --baseHref command line flag with ng serve and ng build this means that you no longer have to prefix the routes in app-routing.module.ts

ng serve --baseHref=/customer/

build with

ng build --baseHref=/customer/