How to setup APP_BASE_HREF DI Token in Angular when Scripts/Assets are being loaded from a CDN

Viewed 548

I currently try to setup an Angular app that is hosted on a domain and gets its scripts and assets from a CDN. The path to the application is www.domain.de/subpath/ (obviously changed for this question) and when I build the application in my CI Pipeline I am using ng build--configuration=${ENV} --base-href=${CDN_URL}. Since with only this setup the app would try to do it's routing on CDN_URL I am trying to utilize the APP_BASE_HREF DI Token as described in the Angular Docs.

However no matter what I setup as DI Token I always get unwanted behavior:

{ provide: APP_BASE_HREF, useValue: `${environment.BASE_URL}/` }
Result when navigating to www.domain.de/subpath/ -> www.domain.de/landing-page

{ provide: APP_BASE_HREF, useValue: `${environment.BASE_URL}/subpath` }
Result when navigating to www.domain.de/subpath/ -> www.domain.de/subpath/subpath/landing-page

DESIRED Result would be: www.domain.de/subpath/ -> www.domain.de/subpath/landing-page

I previously has a a setup that used ng build --configuration=${ENV} --deploy-url=${CDN_URL} --base-href="/subpath/" but deploy-url is deprecated and also only loads scripts from the CDN but not assets.

Is there anything I am missing or is what I want simply not achievable with this simple approach?

1 Answers

I tried for quite sometime to load assets from a CDN URL, and faced a similar issue. This is what I ended up doing :

declare let __webpack_require__: any;

if (environment.production) {
    enableProdMode();
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    // eslint-disable-next-line prefer-const
    const cdnPath = `${environment.BASE_URL}/<subpath>`
    __webpack_require__.p = cdnPath;
}

This updates the webpack's runtime.js path from which the assets are loaded on the fly. It's pretty hacky, but it worked for me.

Related