Skip to content

cstimkong/js-module-loader

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

36 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

JavaScript Module Loader

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.

How to Use

General Usage Patterns

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

Example

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).

Contact

For any questions and suggestions, please contact me via tim.kong@libc.io.

About

Mocked module loader for loading instrumented code

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published