4

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

Metabolic
  • 2,808
  • 3
  • 27
  • 41
  • Still an issue in connection with "route-resolve", see here: https://stackoverflow.com/questions/55355133/angular-7-hot-module-replacement-does-not-work-if-any-route-resolve-involved –  Mar 26 '19 at 10:48

4 Answers4

6

We faced the same problem. It was solved it by removing Webpack related dev dependencies and performing a fresh npm install.

rm -R package-lock.json node_modules npm cache clean --force npm i

Hope it can help.

Iorek
  • 61
  • 3
  • I was having the same problem. I had tried removing my node_modules and re-installing previously, but I think the key was we had some old webpack dev dependencies still in our package.json from pre-CLI days. – wags1999 Oct 09 '18 at 13:28
  • Remove the `package-lock.json` before reinstalling packages! Doh! – The Head Rush Sep 04 '19 at 17:11
  • Indeed we migrated from webpack to angular cli and some dev dependencies were still left in the package.json. – stephan.peters Feb 10 '20 at 09:53
1

A little late to this...what worked for me was in my ClientApp folder I had a /dist folder with all the js bits...HMR won't work if there is a dist folder. The dist gets there if you do a build. Delete the dist folder, then run ng serve. In my case I have a .net core app hosting it so I built that and launched against my angular app...test by modifying html file...app should reload in browser with new content..

swandog
  • 159
  • 1
  • 2
  • 6
  • For me, having the dist folder didn't seem to make a difference. The problem was some old webpack dev dependencies, as suggested by samuel rott. – wags1999 Oct 09 '18 at 13:47
1

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

Metabolic
  • 2,808
  • 3
  • 27
  • 41
  • 1
    Not working for me. In face there is a line `module.hot.accept();` in `hmrBootstrap` function which seems do the same. – Walter Luszczyk Nov 20 '19 at 11:33
  • It can't have solved your problem, maybe something else did. This code line already exists in hmrBootstrap as @WalterLuszczyk suggested. So, calling it again will not make any difference. – Pankaj Jan 17 '20 at 19:17
-1

Here is my setup, currently working just fine under the newest versions. You can get rid of the ngrx stuff if you don't need that :-)

// main.ts

// ...
import { 
  bootloader, createInputTransfer, createNewHosts, removeNgStyles 
} from '@angularclass/hmr/dist/helpers'; // For correct treeshaking    

if (environment.production) {
  enableProdMode();
}

type HmrModule<S> = {
  appRef: ApplicationRef,
}
type HmrNgrxModule<S, A> = HmrModule<S> & {
  store: { dispatch: (A) => any } & Observable<S>,
  actionCreator: (s: S) => A
}

const isNgrxModule = 
  <S, A, M extends HmrNgrxModule<S, A>>(instance: HmrModule<S> | HmrNgrxModule<S, A>)
  : instance is M =>
    !!((<M>instance).store && (<M>instance).actionCreator);

function processModule<S, A, M extends HmrModule<S> | HmrNgrxModule<S, A>>(ngModuleRef: NgModuleRef<M>) {

  const hot = module['hot'];
  if (hot) {

    hot['accept']();

    const instance = ngModuleRef.instance;
    const hmrStore = hot['data'];

    if (hmrStore) {
      hmrStore.rootState 
        && isNgrxModule(instance) 
        && instance.store.dispatch(instance.actionCreator(hmrStore.rootState));
      hmrStore.restoreInputValues && hmrStore.restoreInputValues();
      instance.appRef.tick();
      Object.keys(hmrStore).forEach(prop => delete hmrStore[prop]);
    }

    hot['dispose'](hmrStore => {
      isNgrxModule(instance) && instance.store.pipe(take(1)).subscribe(s => hmrStore.rootState = s);
      const cmpLocation = instance.appRef.components.map(cmp => cmp.location.nativeElement);
      const disposeOldHosts = createNewHosts(cmpLocation);
      hmrStore.restoreInputValues = createInputTransfer();
      removeNgStyles();
      ngModuleRef.destroy();
      disposeOldHosts();
    });
  }
  else {
    console.error('HMR is not enabled for webpack-dev-server!');
    console.log('Are you using the --hmr flag for ng serve?');
  }

  return ngModuleRef;
}

const bootstrap = () => platformBrowserDynamic().bootstrapModule(AppModule);
const hmrBootstrap = () => bootloader(() => bootstrap().then(processModule));

environment.hmr
  ? hmrBootstrap()
  : bootstrap();
// app.module.ts

// ...
export class AppModule {
  constructor(
    public appRef: ApplicationRef 
    // , ...
  ){}
}
// angular.json

"build": {
  "configurations": {
    "hmr": {
      "fileReplacements": [
        {
          "replace": "src/environments/environment.ts",
          "with": "src/environments/environment.hmr.ts"
        }
      ]
    }
  }
},
"serve": {
  "configurations": {
    "hmr": {
      "browserTarget": "AppName:build:hmr"
    }
  }
}

And I run it with ng serve --hmr -c=hmr

I hope this helps a little :-)

Heehaaw
  • 2,677
  • 17
  • 27