The project provide another runtime module loader isolated from the default module loaders (global require
, import()
mechanism), and is easy for instrumenting the code. It is suitable for testing multiple JavaScript modules in an isolated environment.
function loadNodeJSModule(modulePath: string, async: false, options?: LoadOptions): any;
function loadNodeJSModule(modulePath: string, async: true, options?: LoadOptions): Promise<any>;
Parameters are explained as follows:
Parameter | Explanation |
---|---|
modulePath |
Absolute (or relative path to the working directory) to a Node.js module |
async |
Load the module asynchronously (corresponding to import()) or synchronously (corresponding to require calls). |
options |
Additional options (detailed below) |
Supported options:
Option name | Type | Description |
---|---|---|
instrumentFunc |
Function or null |
function for instrumentation, accepting 2 arguments (code string and file name) |
subPath |
string | the subpath of a module to load (e.g., helpers in require('yargs/helpers') ) |
globalThis |
object | the mocked globalThis for executing the initialization code in the loading process |
returnSourceFiles |
boolean | whether to return all included source files |
Suppose that yargs
module is installed at /home/test/yargs
. Now you want to load yargs
via subpath import, you can use loadNodeJSModule
as follows:
const loadNodeJSModule = require('js-module-loader');
let mod = loadNodeJSModule('/home/test/yargs', true, {subPath: 'helpers'});
let hideBin = mod.hideBin;
This is equivalent to the code const { hideBin } = require('yargs/helpers')
(CommonJS) or import { hideBin } from 'yargs/helpers'
(ESM).
For any questions and suggestions, please contact me via tim.kong@libc.io.