Angular 7 Hot reload + Ngrx
There are several articles on this topic, yet neither of them is clear enough / updated with the newest technologies. That is the reason why I have decided to write the following tutorial how to properly set everything up:
NEEDED PACKAGES
There are several packages we are going to need: npm install @types/node npm install @angularclass/hmr
PREPARE BOOTLOADER AND ENVIRONMENT
First, we need to create a new environment that will be used in a new CLI configuration through which the browser will know that we are running in HMR mode. Add property hmr: false to existing environments and create new environment (src/environments/environment.hmr.ts):
https://gist.github.com/JurajMlich/b36c362ca9deb7e8b0edeab6f793cb8d
Second, we need to modify the bootloading process. The CLI generates boostraping process that listenes for DOMContentLoaded event and initializes the angular applicattion in the handler. As hot swap works by "reexecuting every files", we need to load the application even if the event was already triggered. That is what the function bootloader from @angularclass/hmr does. In addition to that, we need to initialize hmrModule and initialize hot module (webpack provided):
https://gist.github.com/JurajMlich/ff18384685811afedbf3d43b20bb0c2c
HMR RELOAD LOGIC
The next thing we need to set up is to tell the browser what to do when hot reloading the application. More specifically, we need to:
- destroy old angular application,
- create identical root element,
- store state and input values,
- restore state in the newly bootstraped angular application.
Luckily, the infrastructure needed for this is already provided by the @angularclass/hmr's hmrModule and we only need to add a three methods to our AppModule class:
https://gist.github.com/JurajMlich/58ed66bb0843afc7ac969a90a77eceba
and create new meta reducer that will process the SET_ROOT_STATE action that has our old store:
https://gist.github.com/JurajMlich/b26629d4b61690960a78eb14afe4a49d
SET UP angular.json
First, we need to modify the build architect by adding a new configuration:
"hmr":{
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.hmr.ts"
}
]
}
Second, we need to modify the serve architect by adding another configuration:
"hmr": {
"hmr": true,
"browserTarget": "PROJECT NAME:build:hmr"
},
WE ARE DONE
Run the HMR configuration by executing the following:
ng serve -c hmr
In case of any questions, I'll be happy to help!
I think I might need to know what
RootState.State
is or what your intent is with its inclusion.I have an automatic signin redirect that gets triggered on reload instead of retaining the state information that'd detect it was already logged in, completely obviating any benefit from this