IfHot Module Replacement has been enabled via theHotModuleReplacementPlugin, its interface will be exposed under themodule.hot property as well asimport.meta.webpackHot property. Note that onlyimport.meta.webpackHot can be used instrict ESM.
Typically, users will check to see if the interface is accessible, then begin working with it. As an example, here's how you mightaccept an updated module:
if(module.hot){ module.hot.accept('./library.js',function(){// Do something with the updated library module...});}// orif(import.meta.webpackHot){import.meta.webpackHot.accept('./library.js',function(){// Do something with the updated library module…});}The following methods are supported...
Accept updates for the givendependencies and fire acallback to react to those updates, in addition, you can attach an optional error handler:
module.hot.accept( dependencies,// Either a string or an array of strings callback,// Function to fire when the dependencies are updated errorHandler// (err, {moduleId, dependencyId}) => {});// orimport.meta.webpackHot.accept( dependencies,// Either a string or an array of strings callback,// Function to fire when the dependencies are updated errorHandler// (err, {moduleId, dependencyId}) => {});When using ESMimport all imported symbols fromdependencies are automatically updated. Note: The dependency string must match exactly with thefrom string in theimport. In some casescallback can even be omitted. Usingrequire() in thecallback doesn't make sense here.
When using CommonJS you need to update dependencies manually by usingrequire() in thecallback. Omitting thecallback doesn't make sense here.
(err, {moduleId, dependencyId}) => {}
err: the error thrown by the callback in second argument or during dependency execution when using ESM dependencies.moduleId: the current module id.dependencyId: the module id of the (first) changed dependency.Accept updates for itself.
module.hot.accept( errorHandler// Function to handle errors when evaluating the new version);// orimport.meta.webpackHot.accept( errorHandler// Function to handle errors when evaluating the new version);When this module or dependencies are updated, this module can be disposed and re-evaluated without informing parents. This makes sense if this module has no exports (or exports are updated in another way).
TheerrorHandler is fired when the evaluation of this module (or dependencies) has thrown an exception.
(err, {moduleId, module}) => {}
err: the error when evaluating the new version.moduleId: the current module id.module: the current module instance.module.hot: allow to use the HMR API of the errored module instance. A common scenario is to self accept it again. It also makes sense to add a dispose handler to pass data along. Note that the errored module might be already partially executed, so make sure to not get into a inconsistent state. You can usemodule.hot.data to store partial state.module.exports: can be overridden, but be careful since property names might be mangled in production mode.Reject updates for the givendependencies forcing the update to fail with a'decline' code.
module.hot.decline( dependencies// Either a string or an array of strings);// orimport.meta.webpackHot.decline( dependencies// Either a string or an array of strings);Flag a dependency as not-update-able. This makes sense when changing exports of this dependency can't be handled or handling is not implemented yet. Depending on your HMR management code, an update to these dependencies (or unaccepted dependencies of it) usually causes a full-reload of the page.
Reject updates for itself.
module.hot.decline();// orimport.meta.webpackHot.decline();Flag this module as not-update-able. This makes sense when this module has irreversible side-effects, or HMR handling is not implemented for this module yet. Depending on your HMR management code, an update to this module (or unaccepted dependencies) usually causes a full-reload of the page.
Add a handler which is executed when the current module code is replaced. This should be used to remove any persistent resource you have claimed or created. If you want to transfer state to the updated module, add it to the givendata parameter. This object will be available atmodule.hot.data after the update.
module.hot.dispose((data)=>{// Clean up and pass data to the updated module...});// orimport.meta.webpackHot.dispose((data)=>{// Clean up and pass data to the updated module...});Calling this method will invalidate the current module, which disposes and recreates it when the HMR update is applied. This bubbles like a normal update of this module.invalidate can't be self-accepted by this module.
When called during theidle state, a new HMR update will be created containing this module. HMR will enter theready state.
When called during theready orprepare state, this module will be added to the current HMR update.
When called during thecheck state, this module will be added to the update when an update is available. If no update is available it will create a new update. HMR will enter theready state.
When called during thedispose orapply state, HMR will pick it up after getting out of those states.
Conditional Accepting
A module can accept a dependency, but can callinvalidate when the change of the dependency is not handleable:
import{ x, y}from'./dep';import{ processX, processY}from'anotherDep';const oldY= y;processX(x);exportdefaultprocessY(y);module.hot.accept('./dep',()=>{if(y!== oldY){// This can't be handled, bubble to parent module.hot.invalidate();return;}// This can be handledprocessX(x);});Conditional self accept
A module can self-accept itself, but can invalidate itself when the change is not handleable:
constVALUE='constant';exportdefaultVALUE;if( module.hot.data&& module.hot.data.value&& module.hot.data.value!==VALUE){ module.hot.invalidate();}else{ module.hot.dispose((data)=>{ data.value=VALUE;}); module.hot.accept();}Triggering custom HMR updates
const moduleId=chooseAModule();const code= __webpack_modules__[moduleId].toString();__webpack_modules__[moduleId]=eval(`(${makeChanges(code)})`);if(require.cache[moduleId]){ require.cache[moduleId].hot.invalidate(); module.hot.apply();}Wheninvalidate is called, thedispose handler will be eventually called and fillmodule.hot.data. Ifdispose handler is not registered, an empty object will be supplied tomodule.hot.data.
Do not get caught in aninvalidate loop, by callinginvalidate again and again. This will result in stack overflow and HMR entering thefail state.
Remove the handler added viadispose oraddDisposeHandler.
module.hot.removeDisposeHandler(callback);// orimport.meta.webpackHot.removeDisposeHandler(callback);Retrieve the current status of the hot module replacement process.
module.hot.status();// Will return one of the following strings...// orimport.meta.webpackHot.status();| Status | Description |
|---|---|
| idle | The process is waiting for a call tocheck |
| check | The process is checking for updates |
| prepare | The process is getting ready for the update (e.g. downloading the updated module) |
| ready | The update is prepared and available |
| dispose | The process is calling thedispose handlers on the modules that will be replaced |
| apply | The process is calling theaccept handlers and re-executing self-accepted modules |
| abort | An update was aborted, but the system is still in its previous state |
| fail | An update has thrown an exception and the system's state has been compromised |
Test all loaded modules for updates and, if updates exist,apply them.
module.hot.check(autoApply).then((outdatedModules)=>{// outdated modules...}).catch((error)=>{// catch errors});// orimport.meta.webpackHot.check(autoApply).then((outdatedModules)=>{// outdated modules...}).catch((error)=>{// catch errors});TheautoApply parameter can either be a boolean oroptions to pass to theapply method when called.
Continue the update process (as long asmodule.hot.status() === 'ready').
module.hot.apply(options).then((outdatedModules)=>{// outdated modules...}).catch((error)=>{// catch errors});// orimport.meta.webpackHot.apply(options).then((outdatedModules)=>{// outdated modules...}).catch((error)=>{// catch errors});The optionaloptions object can include the following properties:
ignoreUnaccepted (boolean): Ignore changes made to unaccepted modules.ignoreDeclined (boolean): Ignore changes made to declined modules.ignoreErrored (boolean): Ignore errors thrown in accept handlers, error handlers and while reevaluating module.onDeclined (function(info)): Notifier for declined modulesonUnaccepted (function(info)): Notifier for unaccepted modulesonAccepted (function(info)): Notifier for accepted modulesonDisposed (function(info)): Notifier for disposed modulesonErrored (function(info)): Notifier for errorsTheinfo parameter will be an object containing some of the following values:
{type:'self-declined'|'declined'|'unaccepted'|'accepted'|'disposed'|'accept-errored'|'self-accept-errored'|'self-accept-error-handler-errored', moduleId:4,// The module in question. dependencyId:3,// For errors: the module id owning the accept handler. chain:[1,2,3,4],// For declined/accepted/unaccepted: the chain from where the update was propagated. parentId:5,// For declined: the module id of the declining parent outdatedModules:[1,2,3,4],// For accepted: the modules that are outdated and will be disposed outdatedDependencies:{// For accepted: The location of accept handlers that will handle the update5:[4]}, error:newError(...),// For errors: the thrown error originalError:newError(...)// For self-accept-error-handler-errored:// the error thrown by the module before the error handler tried to handle it.}Register a function to listen for changes instatus.
module.hot.addStatusHandler((status)=>{// React to the current status...});// orimport.meta.webpackHot.addStatusHandler((status)=>{// React to the current status...});Bear in mind that when the status handler returns aPromise, the HMR system will wait for thePromise to resolve before continuing.
Remove a registered status handler.
module.hot.removeStatusHandler(callback);// orimport.meta.webpackHot.removeStatusHandler(callback);