Skip to content

Instantly share code, notes, and snippets.

@cgatian
Created April 18, 2017 19:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cgatian/2e70a3e6721550e70dd9b23f16fa0513 to your computer and use it in GitHub Desktop.
Save cgatian/2e70a3e6721550e70dd9b23f16fa0513 to your computer and use it in GitHub Desktop.
Angular Module HMR Bootstrap
import { NgModuleRef, ApplicationRef, Type } from '@angular/core';
import { createNewHosts, createInputTransfer, removeNgStyles } from '@angularclass/hmr';
/**
* Adds HMR to an existing Angular Module
*
* Credits & References:
* https://webpack.github.io/docs/hot-module-replacement.html
* https://github.com/AngularClass/angular2-hmr
* https://medium.com/@beeman/tutorial-enable-hrm-in-angular-cli-apps-1b0d13b80130
*
*/
export const hmrBootstrap = (module: any, bootstrap: () => Promise<NgModuleRef<any>>): Promise<NgModuleRef<any>> => {
let ngModule: NgModuleRef<any>;
let appRef: ApplicationRef;
// enable HMR
module.hot.accept();
return bootstrap()
.then(createdModule => {
ngModule = createdModule;
appRef = ngModule.injector.get(ApplicationRef);
})
.then(() => {
let incommingStore = module.hot.data || {};
hmrOnInit(incommingStore);
module.hot.dispose((outboundStore: any) => {
hmrOnDestroy(outboundStore);
hmrAfterDestroy(outboundStore);
});
})
.then(() => ngModule);
/**
* Invoked when HMR first loads and any subsequent refreshes
*/
function hmrOnInit(store: any) {
if (!store) { // || !store.state) {
return;
}
if ('restoreInputValues' in store) {
store.restoreInputValues();
}
// initiate change dectection
appRef.tick();
delete store.state;
delete store.restoreInputValues;
}
/**
*
*/
function hmrOnDestroy(store: any) {
let cmpLocation = appRef.components.map((cmp: any) => cmp.location.nativeElement);
// recreate elements
store.disposeOldHosts = createNewHosts(cmpLocation);
// inject your AppStore and grab state then set it on store
// var appState = this.AppStore.get()
// store.state = { data: 'yolo' };
// store.state = Object.assign({}, appState)
// save input values
store.restoreInputValues = createInputTransfer();
// remove styles
removeNgStyles();
ngModule.destroy();
}
function hmrAfterDestroy(store: any) {
// display new elements
store.disposeOldHosts();
delete store.disposeOldHosts;
// anything you need done the component is removed
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment