Replace a Node.js module with another module without any code changes
MIT License
Replace the return value of require('some-module')
with the return
value of another module in any app without any code changes.
npm install hotswap-module --global
The following three commands all run the script.js
file and replace
any call to require('stream')
with require('readable-stream')
.
If hotswap-module
isn't installed, simply use npx to run it:
npx hotswap-module stream readable-stream script.js
If hotswap-module
is installed globally:
hotswap-module stream readable-stream script.js
If hotswap-module
is installed as a dependency:
HOTSWAP=stream,readable-stream node -r hotswap-module script.js
If the script for which you wish to hotswap a module is being started
indirectly, e.g via npm test
, you can use the NODE_OPTIONS
environment variable to require the hotswap-module
:
HOTSWAP=stream,readable-stream NODE_OPTIONS="-r hotswap-module" npm test
const hotswap = require('hotswap-module')
// Call hotswap() with the name of the module you wish to replace and
// the exports object of the replacement module
hotswap('stream', require('readable-stream'))
hotswap-module <old-module> <new-module> <script>
hotswap(name, exports)
Arguments:
name
- The name of the module you whish to replaceexports
- The new value of the modules exports objectIt's important that you call the hotswap
function before the module
defined by name
is required for the first time.