Getting Started with an exciting new feature of Angular 11 — The Hot Module Replacement (HMR)

Sumit Kumar
4 min readMar 12, 2021

--

If you’re an Angular developer, you must’ve faced this issue of reloading the entire web page even when you’re updating just a single module (e.g., the label of your text field) every time you hit the save button. This could become a little frustrating and result in huge time loss and can make the entire development process slow.

Hot Module Replacement in Angular 11

With the Hot Module Replacement (HMR) enabled, a developer can add, update or remove a module without the full page reload. This speeds up production by shortening the delivery time of the entire application. Enabling HMR in your project can result in one of the following:

· Allowing changes to be saved when reloading or rollback completes, since the data could be lost during the full reload

· Saves a lot of developer time by only allowing a portion to get updated

· The change is almost instantaneous, which is just about the same as using the browser’s developer console for changing style elements

In order to add this feature to an existing Angular project, we can use the NGXS HMR plugin available at https://www.ngxs.io/plugins/hmr

Installing HMR

Run the following command over angular CLI to install it:

#npm i @ngxs/hmr-plugin @angularclass/hmr — save-dev

Adding Environment for HMR

In this step, we’ll edit our Angular CLI settings to define the environment in which we want to enable HMR.

To do this, first, locate the directory src/environments/ in your project and create a new file src/environments/environment.hmr.ts with the following content:

    export const environment = {    production: false,    hmr: true};

The next step is to update the production file in the environments directory src/environments/environment.prod.ts as follows:

 export const environment = {  production: true,  hmr: false };

Lastly, we edit src/environments/environment.ts and change the environment to:

export const environment = {    production: false,    hmr: false};

Updating Angular.json

Updating angular.json file is required to enable HMR whenever we build and serve the project. To do that, just add the following HMR configuration under build and serve properties as follows:

  "build": {         "configurations": {          ...          "hmr": {          "fileReplacements": [           {             "replace": "src/environments/environment.ts",             "with": "src/environments/environment.hmr.ts"           }        ]      }     }   },        ...        "serve": {        "configurations": {        ...        "hmr": {        "hmr": true,        "browserTarget": "<project-name>:build:hmr"    }  }}

Here, the <project-name> suggests the name of your angular project.

Next, we should add types to src/tsconfig.app.json as “node”

 {   ...  "compilerOptions": {   ...  "types": ["node"]  }, }

Now, run ng serve with the flag — configuration hmr to enable hmr and select the new environment:

#ng serve — configuration hmr

If we want to avoid writing this every time we do ng serve, just add a shortcut inside the package.json file as below:

 "scripts": {  ... "hmr": "ng serve --configuration hmr"}

Adding Dependency and Configuring our App

In order to get HMR working, we need to install the dependency and configure our app to use it.

Install the @ngxs/hmr-plugin package as a dev-dependency and Update src/main.ts to use the file we just created:

 import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; import { enableProdMode, NgModuleRef } from '@angular/core'; import { AppModule } from './app/app.module'; import { environment } from './environments/environment';  if (environment.production) {    enableProdMode();  }   const bootstrap = () => platformBrowserDynamic().bootstrapModule(AppModule);  if (environment.hmr) {       import('@ngxs/hmr-plugin').then(plugin => {       plugin.hmr(module, bootstrap).catch((err: Error) =>   console.error(err));  });  } else {  bootstrap().catch((err: Error) => console.log(err));}

After following the above steps, we’ve successfully integrated the HMR feature into our existing Angular project. Now to see the changes we can run the app as:

 npm run hmr

You will see a message about HMR being enabled like below in your terminal.

NOTICE Hot Module Replacement (HMR) is enabled for the dev server.

Voila! Now if you make changes to one of your components, those changes should be visible automatically without a complete browser reload/refresh.

Head to the official documentation of HMR if you want to explore its lifecycle and other configuration details https://webpack.js.org/guides/hot-module-replacement/

Further, you can check out this video https://www.youtube.com/watch?v=f4A58G3iN2A to see the working of HMR enabled web page.

Summary

Hot Module Replacement (HMR) is a great feature that has been added to Angular 11 lately. Not only it reduces the load time, but improves the development time and enhances the overall experience of building better and improved web applications.

References

[1] Hot Module Replacement | Webpack https://webpack.js.org/guides/hot-module-replacement/

[2] HMR on NGXS https://www.ngxs.io/plugins/hmr

--

--

Sumit Kumar
Sumit Kumar

Written by Sumit Kumar

Assistant Professor of Computer Science at The NorthCap University, Gurugram, India.

No responses yet