December 10, 2020

Angular 11: Hot Module Replacement

Angular 11 was released few weeks ago and with it comes a large number of performance upgrades, bugfixes and improved logging. Not only was the upgrade from Angular V10 to V11 painless but I wanted to share with you the new Hot Module Replacement (HMR) feature.
This has been exposed on the CLI if you hadn’t tried it in previous versions, so now is a great time to dive in and give it a go.

 

What’s the Problem?

During normal development of an Angular project, when we save a change, the application is recompiled to re-build and paint the views. Angular is loading modules, CSS, etc again and again even if we do a small change in any file.

This process consumes a lot of time to reflect a minor change on screen as development bundles take much more time than production builds to load in the web-browsers.

Using the HMR feature in Angular

HMR is a Webpack feature to update the application modules without reloading and repainting everything.
By using the HMR technique the application development becomes faster as fewer resources are loaded after saving the changes in the project.
In order to enable HMR when starting an application run the following command:

After the local server starts the console will display a message confirming that HMR is active:
NOTICE: Hot Module Replacement (HMR) is enabled out of the box for the dev server.

 

Classic Angular Reloading

The above example should look very common for frontend developers. You fill out your form with data , and then for some reason you decide to make a minor adjustment in your stylesheet or template. By doing so, it forces the whole app to rebuild, refresh the page and display the new version of our app.
Therefore the input fields are cleared which means we lose our state.

 

Hot Module Replacement in Angular

With the hot module replacement flag used we see a slightly different behavior.
The initial flow is the same. However when we make our change in the template, we see that only the affected part in our app is reloaded.
This time the hot module replacement preserves our state and our input still has our user generated value. Noice!

 

Conclusion

By implementing the Hot Module Replacement technique we can save much time, which would otherwise be wasted during the development phase. It is one of the most important features provided by Webpack.

Related Posts

fahem@w11k.de
Developer at thecodecampus </>


Leave a Reply

Add code to your comment in Markdown syntax.
Like this:
`inline example`

```
code block
example
```

Your email address will not be published.