网页 综合 更新时间 2026-11-14 09:18:26

Hot Module Replacement | webpack

自动蜘蛛 webpack.js.org 正文约 6000 字
Hot Module Replacement | webpack
This guide extends on code examples found in the Development guide.
Hot Module Replacement (or HMR) is one of the most useful features offered by webpack. It allows all kinds of modules to be updated at runtime without the need for a full refresh. This page focuses on implementation while the concepts page gives more details on how it works and why it's useful.
HMR is not intended for use in production, meaning it should only be used in development. See the building for production guide for more information.
This feature is great for productivity. All we need to do is update our webpack-dev-server configuration, and use webpack's built-in HMR plugin. We'll also drop the print.js tag from the page, as that module will now be consumed by index.js.
Since webpack-dev-server v4.0.0, Hot Module Replacement is enabled by default.
If you took the route of using webpack-dev-middleware instead of webpack-dev-server, please use the webpack-hot-middleware package to enable HMR on your custom server or application.
you can also provide manual entry points for HMR:
You can use the CLI to modify the webpack-dev-server configuration with the following command: webpack serve --hot-only. T> output.htmlFilename resolves [name] from the page's own filename, so the emitted document stays index.html whatever the entry is called.
Now let's update the index.js file so that when a change inside print.js is detected we tell webpack to accept the updated module.
Start changing the console.log statement in print.js, and you should see the following output in the browser console (don't worry about that button.onclick = printMe output for now, we will also update that part later).
When using Webpack Dev Server with the Node.js API, don't put the dev server options on the webpack configuration object. Instead, pass them as a second parameter upon creation. For example:
new WebpackDevServer(options, compiler)
To enable HMR, you also need to modify your webpack configuration object to include the HMR entry points. Here's a small example of how that might look:
See the full documentation of webpack-dev-server Node.js API.
If you're using webpack-dev-middleware, check out the webpack-hot-middleware package to enable HMR on your custom dev server.
Hot Module Replacement can be tricky. To show this, let's go back to our working example. If you go ahead and click the button on the example page, you will realize the console is printing the old printMe function.
This is happening because the button's onclick event handler is still bound to the original printMe function.
To make this work with HMR we need to update that binding to the new printMe function using module.hot.accept:
This is only one example, but there are many others that can easily trip people up. Luckily, there are a lot of loaders out there (some of which are mentioned below) that will make hot module replacement much easier.
Most HMR confusion comes from one wrong assumption: that an update re-runs the module you wrote the accept call in. It does not.
When a module changes, webpack walks up from it through the modules that imported it until it finds one that accepted the change. Only the changed module is re-executed. The module that accepted it keeps running — the same instance, the same variables, the same closures — and its callback is invoked so it can react. accept('./dep.js', cb) therefore means "I will deal with ./dep.js changing", not "re-run me when it changes".
Two consequences follow, and they are the whole of HMR in practice:
These examples use import.meta.webpackHot, which works whether the module ends up auto-detected or strict ESM. module.hot is the equivalent, and the only spelling in CommonJS, but it is unavailable in a strict ESM module. Both are erased in a production build, so the if guard keeps the code out of your bundle.
A module that has no outward-visible bindings — it only causes effects when it runs — can accept its own changes. Webpack then re-executes that module in place and the update stops there instead of bubbling to the entry point.
This is what stylesheets do, and it is the right choice for things like a registered route table, a set of chart definitions, or a <canvas> render loop. It is the wrong choice when other modules hold on to what this one exported: they captured the old value at import time, and re-running the module does not update their copies. Accept in the module that owns the reference instead.
Re-executing a module runs its side effects a second time. An interval gets scheduled twice, a listener is registered twice, a socket is opened again — after ten edits the page has ten of everything and looks "slow" or "flickery" for reasons that have nothing to do with webpack.
dispose is the release valve. It runs before the new version executes, so it is where you undo what the current version claimed:
The rule of thumb: anything that outlives the module's own evaluation — timers, listeners, sockets, observers, DOM nodes appended to document, entries added to a global registry — needs a matching line in dispose.
The data object passed to dispose is handed to the next version of the module as import.meta.webpackHot.data, which is undefined on the first run. That round trip is how an edit keeps the state it should keep — a scroll position, a form draft, a game's score, the frame counter of an animation:
Edit this module and the counter carries on from where it was instead of restarting at zero — dispose stops the old interval and stashes the value, then the new version reads it back out of data.
data is transferred as the same object, not serialized, so a live handle put there survives — but so does anything it keeps alive. Copy out the values you need rather than stashing whole component trees.
A store, a router, a DI container: something created once that the whole application holds a reference to. Replacing the object itself would strand every holder on the old one, so replace its contents instead and leave the identi
访问原文 返回搜索 https://webpack.js.org/guides/hot-module-replacement/
本页为82搜索生成的网页快照,内容来自站内索引;演示数据的原文链接仅作示例。