During normal development of an Angular project, the application is again and again recompiled to re-build and paint the views, loading modules, CSS etc even on small changes made and saved.
As development builds take much time than the production builds, it consumes lot of time to reflect the minor changes on display of web browsers. So angular released a good method to overcome this delay.
Hot Module Replacement (HMR) is a key web pack feature that is not enabled by default in Angular. It allows module replacement without full page refresh. This helps in retaining much of the application state, usually lost when reloading. It also saves valuable time by only updating what has changed. Code changes also reflect instantly, like when you are messing with dev tools on the browser.
First, we need to create a separate environment for hmr inside src/environment folder at the root of your project. And add the following code.
After that, we have to change the angular configuration and add this environment for both our build and serve properties. To do this, open Angular Json from the root of your angular workspace. Under the r build property, add new configuration lines for HMR, with the content below:
Then update your existing environment files. And set hmr to false in both the files
Create hmr.ts file next to main.ts inside src folder. And add the following code inside it.
Then allow main.ts to use hmr.ts file
Now we can serve our angular application with hmr enabled using the following command.
ng serve –configuration hmr
Now the angular application will be running in Hot Module Replacement mode. If we make changes to the HTML & template files, it will be loaded very faster on the screen. And it will be very helpful for angular web development.