HMR
Hot Module Replacement (HMR) is a Webpack feature to update code in a running app without rebuilding it. This results in faster updates and less full page-reloads. In order to get HMR working with Angular CLI we first need to add a new environment and enable it.
Add environment for HMR
In this step we will configure the Angular CLI environments and define in which environment we enable HMR. We will start out by adding and changing files in the src/environments/
directory. First we create a file called src/environments/environment.hmr.ts
with the following contents:
Update src/environments/environment.prod.ts
and add the hmr: false flag to the environment:
Lastly we edit src/environments/environment.ts
and change the environment to:
Update angular.json to include an hmr environment as explained here and add configurations within build and serve to enable hmr. Note that here represents the name of the project you are adding this configuration to in angular.json.
Add the necessary types to src/tsconfig.app.json
Run ng serve with the flag --configuration hmr to enable hmr and select the new environment:
Create a shortcut for this by updating package.json and adding an entry to the script object:
Add dependency and configure app
In order to get HMR working we need to install the dependency and configure our app to use it.
Install the @angularclass/hmr
, @ngxs/hmr-plugin
module as a dev-dependency
Update src/main.ts to use the file we just created:
(OPTIONAL) Update src/app/app.module.ts to manage the state in HMR lifecycle:
Starting the development environment with HMR enabled
Now that everything is set up we can run the new configuration:
Example:
When starting the server Webpack will tell you that it’s enabled:
Now if you make changes to one of your components, those changes should be visible automatically without a complete browser refresh.
HMR lifecycle
If you want to do some modifications to the state during the hmr lifecycle you can use these built-in actions. They will not be executed in production.
Last updated