How to set 'publicPath' in webpack after 'deployUrl' option is deprecated in version 15
https://github.com/angular/angular-cli/blob/5402f99f8ad20e0a57456a416a992415fc6332bd/packages/angular_devkit/build_angular/src/webpack/configs/common.ts#L335
We have a similar case where we define deployUrl (in angular.json) our CDN address, which is then added to all the images and scripts (in index.html and CSS files).
This allows us to load our assets from our CDN, while sending the HTTP requests to our server (the domain that we ran at, while baseHref is '/').
Setting the baseHref to be the CDN domain (without deployUrl) causes our app to send all of the HTTP requests to the CDN instead of to our domain - which breaks the app.
@alan-agius4 - Once deployUrl is deprecated, how can we keep having the CDN defined (like publicPath in WebPack) without breaking the app's HTTP requests?
We have a similar problem without deployUrl. We have had ability to serve 2 different versions, Dev served from local files and Prod served from CDN. The HTML would load files based on deployUrl + fileName while keeping the base context the same. Using baseHref would change the entire page context. In short, they are not equivalent to our use cases.
As a work around for the WebPack publicPath value you can set the global __webpack_public_path__ variable in your angular entry point. I have the following in my main.ts file.
declare var __webpack_public_path__: string;
__webpack_public_path__ = 'valueFormerlyAssignedUsing_deployUrl';
If you have different build configurations you can store the appropriate value in the './environments/environment file and have those be replaced according to the angular.json configuration.
I do want to upvote this question though because it is a breaking change without any angular specific work around. We also use asp.net mvc to host the root file (instead of the angular index.html file) so the angular distribution folder is no the same as the load point url that asp.net uses. This means that anything dynamically loaded with import will fail because it can't be resolved.
We also have a setup that is heavily dependent on deployUrl. In our case, our developers run ng serve on localhost, but load the application on a remote development server that also contains API endpoints, as well as additional js resources unrelated to Angular. By setting deployUrl to //localhost:4200/, and leaving the baseUrl as /, we can get the behavior we need, in a way that most closely resembles our production code.
Then, for production, we deploy all of our angular code to a subdirectory dedicated to the code generated by Angular. Setting deployUrl to https://our.staticdomain.com/angular/ also perfectly suits our needs.
I'm not sure how we would handle this if we couldn't set deployUrl.
@karptonite - does setting __webpack_public_path__ instead of deployUrl solve your problem? See also this previous comment
@IgorWolbers it does seem to solve it, although I would, as you suggest, have to mess with environments to get it to work for both development and production.
But setting a webpack variable globally like that seems like a brittle solution--theoretically, an angular user could be agnostic with regard to the build system, aside from the options in angular.json.
@karptonite
it does seem to solve it, although I would, as you suggest, have to mess with environments to get it to work for both development and production.
I have it configured that way in our code and it runs well. It is the most flexible option AFAIK.
But setting a webpack variable globally like that seems like a brittle solution--theoretically, an angular user could be agnostic with regard to the build system, aside from the options in angular.json.
True but then you would likely not have this error to begin with as deployUrl never integrated with other build systems in this manner other than WebPack AFAIK.
You are correct that the solution is not elegant, it is not (well) documented, and it would be nicer to call an angular specific API that would do this for you like deloyUrl used to do. That said at least there is a work around that can be used in the interim. Let's hope that the angular team rethinks their plans for deployUrl.
@alan-agius4 Our use case is also CDN. The application itself is hosted through ASP.NET, where style and scripts are from CDN. Same as few others, where base href won't help, as we don't want API traffic goes to CDN.
If we use GitHub as an example, their CSS style assets is under https://github.githubassets.com/assets/dark-xxxx.css. Their script is also from similar location. Such as https://github.githubassets.com/assets/chunk-frameworks-xxxx.js.
Where GitHub's route is under https://github.com/angular/angular-cli/issues/22113.
It is common for many SPA to choose such approach. Where assets location is different to the application location. This is not unreasonable requirement, also with CI/CD, how many really care about how long it takes to build if it is required for an essential approach they want to achieve?
We have a somewhat special use case with the Magnolia CMS, which has an SPA Editor with support for Angular. We also use SSR, which means that Angular Universal and Magnolia are running side-by-side, with the Universal-Server being the entrypoint for both e.g. website and CMS (for the authors).
When using the author pages of the CMS, Magnolia will consume the index.html and change the base-href to the current page, before returning it to the user. This in turn means that our scripts (runtime.js, vendor.js etc.) in the body won't be resolved correctly when we cannot use absolute paths.
That is why we rely on being able to specify this absolute path with deployUrl.
TL;DR
Our page can be accessed through different baseHrefs, that depend on the context from where they are accessed, and that means we need absolute paths in our resources to be able to load them from the same location all the time.
We too rely heavily on deployUrl with the same CDN use case as i see mentioned often here, Should deprecating deployUrl perhaps be reconsidered, it appears to be widely used and needed
I'll add my 2 cents: we don't use Angular-generated index.html to serve the app, we use Rails instead. So, previously we used --deploy-url to point to Webpack Dev Server for ng serve and to point to CDN for production build (ng build).
Now angular team suggests to use a combination of base href and APP_BASE_HREF instead of deploy-url option, but it just doesn't work without introduction of many ugly hacks. Let's take a "production build" case as an example. Here is the list of things we have to do:
- Set
<base href>tohttps://some.cdn.com/for all the assets to be served correctly. - Set
APP_BASE_HREFtolocation.originin order for the router to behave correctly - (hack) Prepend app host to all the resource urls that should point to the apps root e.g.
<link href="https://my-app.com/manifest.json" rel="manifest">,<meta content="https://my-app.com/browserconfig.xml" name="msapplication-config">etc. as without it they'll be loaded from CDN. - (hack) Introduce a
IgnoreBaseHrefInterceptorwhich will prependlocation.originto all requests because without it all of them will go tohttps://some.cdn.com/(browser uses<base href>value also for all XHR requests).
export class IgnoreBaseHrefInterceptor implements HttpInterceptor {
intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
if (request.url.startsWith('/')) {
request = request.clone({
url: `${location.origin}${request.url}`,
});
}
return next.handle(request);
}
}
- (hack) Change all the code that uses
location.href/replaceto use absolute URLs (prependlocation.origin). Without it browser will prepend<base href>to all of them and redirect user to CDN.
Frankly speaking, all this looks like a very doubtful alternative to a simple --deploy-url option and I would definitely vote for leaving it for ng build and returning it back for ng serve.
After reading the comment of @alan-agius4 again. He said following.
the
deployUrl, is used not just to set thepublicPath, usingdeployUrlwill cause additional steps including processing all CSS templates and files to append thedeployUrlto the assetsurls.
How many people here that need --deployUrl to make angular application functional on CDN care about assets? Personally I don't.
To be clear, I host all the assets directly on CDN, not within the repository to be deployed through assets. So, for my scenario, --deployUrl only means for CSS, JS bundles. Not for image, fonts, SVG or any other assets.
- CSS bundle produced by Angular builds (
I do care) - JS bundle produced by Angular builds to allow lazy load (
I do care) - Fonts (
don't care): For most of people that uses either Rails, ASP.NET or other to power the index.html, we normally have link directly to the fonts we need. - Images in CSS or Images in HTML template (
don't care): If host in CDN instead of from assets folder, we can include full link in CSS, or create Angular directive to use relative URL to translate to CDN link. Not an problem. - SVG (
don't care): Same as image, or we could use approach similar to Font Awesome, save definition in TS and load it through component.
So, alternative approach is to introduce another parameter to allow deploy URL only for JS, CSS and templates, ignore assets. That way, Angular CLI does not have to process anything related to assets, nor it will have much burden of package size.
@th0r expanded what @alan-agius4 have suggest to use base-url to get around. Which is great, but it also reveal many hacks that need to be done. Base URL will cause router to broke, cause XHR/fetch to broke on relative URL. Agree with @th0r, I wouldn't count that as solution either.
I would try to provide few solution as well, some of them require angular team's implementation, which I will list here as potential get around.
- Introduce another feature that's similar to
--deploy-url. It only care about lazy load. It will resolve any template, CSS, JS that's related to lazy loading and ignore all assets, such as font, image, SVG etc. (Depending on Angular team)- Assets such as image, font and SVG always have alternative way to achieve. Those items are under our reach.
- Lazy loading module does not under our control. Which should be something for angular team to cover.
- Down side is people who rely on
--deploy-urlfor assets will suffer.
- Introduce an angular config that can setup at run time. Similar to
APP_BASE_HREF. Where we can define an CDN root path for lazy loading module to use. (Depending on Angular team)- Similar pro and con to first approach.
- Best build time, same without
--deploy-urland less bundle size.
- Server side, Rails or ASP.NET, when we define angular application route, we use route definition to allow all child route to hit. Such as
Route("app/v2/{*appCacheAll}"). What we can do is to detect income request, if it ends with.jsor.css. We can respond with redirect to CDN response rather than content ofindex.html.- Problem 1 with such approach. If deploy location is based on version, then we need a way to understand which version the app is asking. Often happen during upgrade. Solution can be use cookie to give latest version number, then each JS and CSS query will contain version info.
- Problem 2. Retrieve performance. Since it is redirect, it means browser will first contact with server, then redirect to actual assets.
- Benefit is it can also apply to assets without client side hack.
- Similar as solution 3, when detect
.jsor.cssrequest, instead of relocated response, server act as proxy to assets.- Problem with such approach is defeat purpose of CDN. Also require better code to handle proxy correctly, to make server side memory efficient also utilize cache header.
- Benefit of such approach is that, all JS and CSS files will be treated as if they are under that path. It is not redirect.
That's all the solutions I can think of. First two solution depends on Angular team, where last 2 require backend skill. Which is what I am familiar with. Add @th0r's solution on top of it. Which is five different ways. So, if Angular team removed without introduce alternative way such as 1st and 2nd solution, we have at least one front end solution and two back-end solution.
This will cause us a lot of discomfort as we rely on deployUrl heavily while building our production bundle.
We set the value as deployUrl: https://some-cdn.com/ where are JS and CSS artifacts are stored. Our baseHref is completely different from the deployUrl value.
Coming up with alternatives to this will be complex and will involve some tradeoffs (be it writing a script for the postbuild option or using fileReplacements to replace the .html to name a few).
As a work around for the WebPack
publicPathvalue you can set the global__webpack_public_path__variable in your angular entry point. I have the following in mymain.tsfile.declare var __webpack_public_path__: string; __webpack_public_path__ = 'valueFormerlyAssignedUsing_deployUrl';If you have different build configurations you can store the appropriate value in the
'./environments/environmentfile and have those be replaced according to theangular.jsonconfiguration.I do want to upvote this question though because it is a breaking change without any angular specific work around. We also use asp.net mvc to host the root file (instead of the angular index.html file) so the angular distribution folder is no the same as the load point url that asp.net uses. This means that anything dynamically loaded with
importwill fail because it can't be resolved.
@IgorWolbers didn't work for me though.
// main.ts
declare var __webpack_public_path__: string;
if (environment.production) {
__webpack_public_path__ = 'https://some-cdn.com/';
enableProdMode();
}
platformBrowserDynamic().bootstrapModule(AppModule)
.catch(err => console.log(err));
after running ng build, we get:
<script src="runtime.71b88e53f069c658.js" instead of <script src="https://some-cdn.com/runtime.71b88e53f069c658.js"
@aashwath - that is expected as this is for runtime behavior not for build time behavior (generation of the index.html file). If your index.html, or whatever .html file you are using to load angular, is not in the same location as the angular javascript output files then you need to update that .html file accordingly. AFAIK none of the proposed work arounds will do that for you automatically. All I can think of is a custom gulp script but maybe there is a better solution I am unaware of.
I suggest angular official dev team to keep deployUrl option, becasue baseHref and deployUrl are not same usage to work, there's no reason to suggest one to become the replacement of another.
I really don't see why this was forced on the build. Listen guys, not everyone hosts the Angular way. There's nothing wrong with keeping the deployUrl option for those of us who need it. It doesn't play well with ng serve but that's fine, I just don't use ng serve. Don't make me hardcode the deployUrl all over the place to get this thing functional again.
I'll add to the list of replies, please don't deprecate/remove this option. Our application run from a .Net MVC razr view with assets hosted elsewhere, so the baseHref for routing is separate from what deployUrl does. You should assume having the base html page / routing / api calls independent from the assets loading calls is a pretty common use case, and module federation might become a pretty common one too.
I also need the deployUrl for AWS CDN of assets and baseHref to do the routing (i have a fun naming: https://myurl.com/with/team/avengers) ... so the app is hosted on "/with", and use "baseHref": "/with/" in production. My assets are not on "/with" .. but on "https://cdn.myurl.com/"