Hot Module Replacement
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 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 for @angularclass/hmr 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 module as a dev-dependency
Create a file called src/hmr.ts with the following content:
Update src/main.ts to use the file we just created:
Starting the development environment with HMR enabled
Now that everything is set up we can run the new configuration:
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.
Last updated