I recently updated my angular app to the latest versions. And after a night of nightmares of bug, I got everything working except for HMR. I am badly stuck with it. Following are my configurations according to the the HMR Story on Angular CLI wiki:
angular.json
"build": {
"configurations": {
"hmr": {
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.hmr.ts"
}
]
}
}
},
"serve": {
"configurations": {
"hmr": {
"hmr": true,
"browserTarget": "appHit:build:hmr"
},
}
},
hmr.js
import { NgModuleRef, ApplicationRef } from '@angular/core';
import { createNewHosts } from '@angularclass/hmr';
export const hmrBootstrap = (module: any, bootstrap: () => Promise<NgModuleRef<any>>) => {
let ngModule: NgModuleRef<any>;
module.hot.accept();
bootstrap().then(mod => ngModule = mod);
module.hot.dispose(() => {
const appRef: ApplicationRef = ngModule.injector.get(ApplicationRef);
const elements = appRef.components.map(c => c.location.nativeElement);
const makeVisible = createNewHosts(elements);
ngModule.destroy();
makeVisible();
});
};
main.ts
import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app/app.module';
import { environment } from './environments/environment';
import { hmrBootstrap } from './hmr';
if (environment.production) {
enableProdMode();
}
const bootstrap = () => platformBrowserDynamic().bootstrapModule(AppModule);
if (environment.hmr) {
if (module[ 'hot' ]) {
hmrBootstrap(module, bootstrap);
} else {
console.error('HMR is not enabled for webpack-dev-server!');
console.log('Are you using the --hmr flag for ng serve?');
}
} else {
bootstrap().catch(err => console.log(err));
}
I tried the following commands:
ng serve --hmr
ng serve --hmr --configuration hmr
ng serve --configuration hmr
Everything gets compiled on change and even the events fired are cached in browser but nothing happens after HMR logs the following:
[WDS] App updated. Recompiling...
[WDS] App hot update...
I am totally lost at this point. Any kind of help will be very much appreciated. Thanks
I think it might be helpful to some. I solved my issue by updating to Angular version 7 and adding the following line in main.ts for HMR
module['hot'].accept();
As follow:
if (environment.hmr) {
if (module['hot']) {
module['hot'].accept();
hmrBootstrap(module, bootstrap);
} else {
console.error('HMR is not enabled for webpack-dev-server!');
console.log('Are you using the --hmr flag for ng serve?');
}
} else {
console.log('hot');
bootstrap().catch(err => console.log(err));
}
So far HMR has been working completely fine. I did not had time to debug it further but most probably there was dependency incompatibility that might have caused it on my end