hot-module-replacement
v4.0.0
Published
Hot module replacement for Node.js (CommonJS and ESM)
Maintainers
Readme
hot-module-replacement
Hot module replacement for node.js
This module tries to mimic webpack HMR API
Installation
npm install --save-dev hot-module-replacementCommonJS usage
Put this code somewhere in your code to initialise hot reload
require('hot-module-replacement')({
// options are optional
ignore: /node_modules/ // regexp to decide if module should be ignored; also can be a function accepting string and returning true/false
})You need to explicitly mark any subtree as 'hot reloadable' by calling hot.accept()
let foo = require('./util/foo.js');
if (module.hot) {
module.hot.accept('./util/foo', () => {
// if foo.js or any files that foo.js depend on are modified this callback is invoked
foo = require('./util/foo.js'); // by this time module cache entry for 'foo' already cleaned and module reloaded, requiring again is the easiest way of geting reference to new module. We need to assign it to local foo variable to make our local code in this file aware of it.
})
}ESM usage (Node >= 22.15)
Requires module.registerHooks (Node 22.15+). CommonJS HMR works on Node 18+.
Static imports are rewritten to mutable let bindings and import.meta.hot.accept('./dep') gets an auto-generated refresh callback.
node --enable-source-maps --import hot-module-replacement/register ./server.mjsimport routes, { a } from './routes.js';
app.use('/', routes);
if (import.meta.hot) {
import.meta.hot.accept('./routes.js'); // `routes` and `a` refresh automatically
}See examples/esm/ (repo dev: npm start; after install from npm: npm run start:package).
Similar projects:
- https://github.com/laverdet/dynohot — full live bindings via generator-based module runtime (heavier, closer to webpack)
- https://github.com/Julien-R44/hot-hook
- https://github.com/yyrdl/dload ( forces you to use own module api for replaceables modules )
- https://github.com/rlindskog/solit ( transpiles all files on start )
- https://github.com/fgnass/node-dev
webpack hmr on the server
- https://github.com/palmerhq/backpack
- https://hackernoon.com/hot-reload-all-the-things-ec0fed8ab0
- https://github.com/jaredpalmer/razzle
- https://github.com/jlongster/backend-with-webpack ( and http://jlongster.com/Backend-Apps-with-Webpack--Part-III )
