This article goes over how to set up Hot Module Replacement (HMR) with Webpack Dev Server (WDS).
Prerequisite
Set up an app with webpack-dev-server.
We are using the package.json
dependencies:
{
"devDependencies": {
"webpack": "^5.35.0",
"webpack-cli": "^4.6.0",
"webpack-dev-server": "^3.11.2"
}
}
Quickstart
Enable HMR for WDS using the CLI by passing --hot
and --inline
:
npx webpack serve --hot --inline
Start the server:
npm start
Output:
> @ start path/to/project
> webpack serve --hot --inline
ℹ 「wds」: Project is running at http://localhost:8080/
ℹ 「wds」: webpack output is served from /
ℹ 「wds」: Content not from webpack is served from path/to/project
⚠ 「wdm」: asset main.js 160 KiB [emitted] [minimized] (name: main) 1 related asset
Open http://localhost:8080/
in the browser:
open http://localhost:8080/
See the console logs:
[HMR] Waiting for update signal from WDS...
[WDS] Hot Module Replacement enabled.
[WDS] Live Reloading enabled.
But that’s not enough for HMR to work. You’ll need to accept the hot update:
// src/index.js
// ...
if (module.hot) {
module.hot.accept();
}
Edit and save the file and the page should update without a hard reload.
You should see the console logs:
[WDS] App updated. Recompiling...
[WDS] App hot update...
[HMR] Checking for updates on the server...
[HMR] Updated modules:
[HMR] - ./src/index.js
[HMR] App is up to date.
Config
HMR can also be enabled from the config file:
// webpack.config.js
module.exports = {
devServer: {
hot: true,
inline: true,
},
};
Run webpack-dev-server
without passing any options:
npx webpack serve