Hot Module Replacement with Angular 2 and Webpack

February 01, 2017 0 Comments webpack, npm

Hot Module Replacement with Angular 2 and Webpack



This article shows how HMR, or Hot Module Replacement can be used together with Angular 2 and Webpack.

Code: Visual Studio 2015 project | Visual Studio 2017 project

Blogs in this series:

package.json npm file

The webpack-dev-server from Kees Kluskens is added to the devDependencies in the npm package.json file. The webpack-dev-server package implements and supports the HMR feature.

"devDependencies": {
  "webpack": "^2.2.1",
  "webpack-dev-server": "2.2.1"

In the scripts section of the package.json, the start command is configured to start the dotnet server and also the webpack-dev-server with the -hot and the -inline parameters.

See the webpack-dev-server documentation for more information about the possible parameters.

The dotnet server is only required because this demo application uses a Web API service implemented in ASP.NET Core.

"start": "concurrently \"webpack-dev-server --hot --inline --port 8080\" \"dotnet run\" "

webpack dev configuration

The devServer is added to the module.exports in the This configures the webpack-dev-server as required. The webpack-dev-server configuration can be set here as well as the command line options, so you as a developer can decide which is better for you.

devServer: {
    historyApiFallback: true,
    contentBase: path.join(__dirname, '/wwwroot/'),
    watchOptions: {
        aggregateTimeout: 300,
        poll: 1000

The output in the module.exports also needs to be configured correctly for the webpack-dev-server to work correctly. If the './' path is used in the path option of the output section, the webpack-dev-server will not start.

output: {
    path: __dirname +  '/wwwroot/',
    filename: 'dist/[name].bundle.js',
    chunkFilename: 'dist/[id].chunk.js',
    publicPath: '/'

Running the application

Build the application using the webpack dev build. This can be done in the commnad line. Before building, you need to install all the npm packages using npm install.

$ npm run build-dev

The npm script build-dev is defined in the package.json file and uses the webpack-dev script which does a development build.

"build-dev": "npm run webpack-dev",
"webpack-dev": "set NODE_ENV=development && webpack",

Now the server can be started using the start script.

$ npm start

The application is now running on localhost with port 8080 as defined.


If for example, the color is changed in the app.scss, the bundles will be reloaded in the browser without refreshing.

Links View story at

Tag cloud