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

3

5

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

Deena answered 12/6, 2019 at 8:40 Comment(0)
M
11

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/
Mure answered 12/6, 2019 at 8:43 Comment(4)
The application failed to load due to "localhost:4200/customer/runtime.js". It is not routing but it sets the relative path.Deena
ng serve --baseHref=/customer/Mure
Works for me when setting up a "Your First App" angular 7 project then used ng serve --baseHref=/customer/. The url localhost:4200/customer works without any errorRim
It only works for me when I write the flag in the following way: ng build --base-href=/customer/Onomatology
C
1

You can use --deploy-url parameter in ng build command.

Example: ng build --deploy-url /my/assets

More detail on https://angular.io/guide/deployment.

Cautionary answered 9/7, 2021 at 11:20 Comment(2)
The tooling says that this approach is now deprecated.Zapata
@Zapata no, it does not says thisPrelude
A
0

I got exactly same bug when I migrate from angular 5 to 7. It is probably related to the way that angular attaching the build js files. If you already added <base href="/"> into index.html but the scripts are still loading from the relative path, it might because there is no <body> tag. Try add <body> tag into index.html file and see if it works.

Aluino answered 9/9, 2019 at 6:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.