Created
April 18, 2017 19:24
-
-
Save cgatian/2e70a3e6721550e70dd9b23f16fa0513 to your computer and use it in GitHub Desktop.
Angular Module HMR Bootstrap
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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