Webpack — Hot module replacement notes

As I know so far there are three ways in Webpack that can auto-compile your code whenever you make a change.

1 . Webpack watch mode

2 . Webpack dev server

3 . Webpack dev middleware

The top two are kind of common ways to deal with this. But their downsides are:

1 . Watch mode will compile your code into a bundle file and save it at your local repository which slows down your loading speed. Plus, you gonna go to manually refresh your browser in order to see the changes.

2 . Webpack dev server is a pretty handy tool to deal with. Because it builds a mini server for you to compile your code and auto-refresh your browser once you make a change. But, this is good for front-end development. What about we want to build our own server? There is no way to run two servers at the same time, while one of them just used to auto-refresh my browser?!

So, after some research, I think the dev middleware should be my best bet. It allows me to run my own server with the compiler from Webpack, and my bundle files will be saved into memory instead of the local repo ( faster loading speed ).

Set it up!

Webpack-dev-middleware comes together with webpack-hot-middleware. One to make the connection with our customized server, and one for hot module replacement ( auto-refresh ).

Middleware setup in the server

Webpack.config.js file

Don’t forget to put this at the bottom of your frontend JS root file

The code above is saying, if the current module is a hot module ( something changed ), then we accept it changes and load it.