webpack-dev-server and HMR

webpack · Practical · 12 min

A fast feedback loop during development depends on the dev server setup.

webpack-dev-server compiles your app in memory (nothing is written to dist/), serves it, and pushes updates to the browser over a WebSocket. Start it with npx webpack serve.

Configuration lives under devServer:

  • port, host, open.
  • hot: true (the default): hot module replacement. Changed modules are swapped in place when an HMR boundary accepts them; otherwise the page reloads (liveReload). CSS through style-loader updates instantly. For React, add @pmmmwh/react-refresh-webpack-plugin with react-refresh for state-preserving component updates.
  • static: folders served as-is (like public/).
  • historyApiFallback: true: serve index.html for unknown paths, required for client-side routers.
  • proxy: an array of rules forwarding API calls to a backend: [{ context: ["/api"], target: "http://localhost:8000" }].
  • client.overlay: show build errors over the page.

In plain modules, the HMR API is module.hot (CommonJS style) or import.meta.webpackHot (ESM): accept, dispose, invalidate.

For server-rendered apps or custom servers, webpack-dev-middleware and webpack-hot-middleware integrate the same features into Express. Like any dev server, never expose it to the internet.

Example

// webpack.config.js (excerpt)
module.exports = {
  mode: "development",
  devServer: {
    port: 3000,
    open: true,
    hot: true,
    static: "./public",
    historyApiFallback: true,           // SPA routes -> index.html
    proxy: [
      {
        context: ["/api"],
        target: "http://localhost:8000",
        changeOrigin: true,
        pathRewrite: { "^/api": "" },   // /api/users -> /users
      },
    ],
    client: { overlay: { errors: true, warnings: false } },
  },
};
// $ npx webpack serve
// <i> [webpack-dev-server] Project is running at: http://localhost:3000/

Remember

  • webpack serve builds in memory and serves with HMR
  • historyApiFallback for client-side routing
  • proxy is an array of { context, target } rules
  • React needs react-refresh-webpack-plugin for Fast Refresh

Watch out for

  • Looking for dev-server output in dist/; it only exists in memory.

Check yourself

  1. A React Router app shows 404 when reloading /settings in dev. Which option fixes it?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: webpack.js.org/configuration/dev-server/