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 loadModule(modulePath: string, options?: LoadOptions): any;
function loadModuleAsync(modulePath: string, options?: LoadOptions): Promise<any>;The second format is to load the module asynchronously (corresponding to import()).
Parameters are explained as follows:
| Parameter | Explanation |
|---|---|
modulePath |
Absolute (or relative path to the working directory) to a Node.js module |
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 |
cache |
object | the cache object in loading the module |
patchExportDefault |
object | whether to return the default export separately |
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 mail AT dezhen DOT org.