|
| 1 | +# Hot module replacement example |
| 2 | + |
| 3 | +A minimal [Express](https://expressjs.com/) server that uses |
| 4 | +`webpack-dev-middleware` with the `hot` option to enable hot module replacement |
| 5 | +over [Server-Sent Events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events). |
| 6 | + |
| 7 | +## What it shows |
| 8 | + |
| 9 | +- Enabling HMR with a single `{ hot: true }` option. |
| 10 | +- Wiring the browser runtime shipped as `webpack-dev-middleware/client` as a |
| 11 | + webpack entry, together with `HotModuleReplacementPlugin`. |
| 12 | +- Accepting updates with `module.hot.accept` so edits apply without a full |
| 13 | + page reload. |
| 14 | + |
| 15 | +## Files |
| 16 | + |
| 17 | +| File | Purpose | |
| 18 | +| ------------------- | --------------------------------------------------------------- | |
| 19 | +| `server.js` | Express server mounting the middleware with `hot: true`. | |
| 20 | +| `webpack.config.js` | Adds the client runtime entry and `HotModuleReplacementPlugin`. | |
| 21 | +| `src/index.js` | App entry that accepts updates via `module.hot`. | |
| 22 | +| `src/render.js` | The module you edit to see HMR in action. | |
| 23 | +| `public/index.html` | Demo page that loads the bundle. | |
| 24 | + |
| 25 | +## Running |
| 26 | + |
| 27 | +From the repository root, build the package first so `dist/` and `client/` |
| 28 | +exist (the example imports `webpack-dev-middleware` and |
| 29 | +`webpack-dev-middleware/client` by name): |
| 30 | + |
| 31 | +```bash |
| 32 | +npm run build |
| 33 | +node examples/hot/server.js |
| 34 | +``` |
| 35 | + |
| 36 | +Then open <http://localhost:3000> and edit `examples/hot/src/render.js`. The |
| 37 | +page updates in place — no reload. |
| 38 | + |
| 39 | +Open your browser's console to see the client runtime log the HMR lifecycle |
| 40 | +(`[webpack-dev-middleware] connected`, `App is up to date.`, …). Server-side |
| 41 | +logs (`Client connected`, build status) are printed through webpack's |
| 42 | +[infrastructure logger](https://webpack.js.org/configuration/other-options/#infrastructurelogging); |
| 43 | +set `infrastructureLogging: { level: "log" }` in the webpack config to see them. |
0 commit comments