1.4.2 • Published 4 months ago

context-require v1.4.2

Weekly downloads
5
License
MIT
Repository
github
Last release
4 months ago

Creates a new require function which runs all required modules in a context other than global. Supports custom require extensions and resolvers. Useful for things like mocking the package.json browser field without a bundler and using JSDOM (without using jsdom global) along side the native commonjs require system.

Although other uses are possible this module was built to run tests in a browser like context with out using a bundler. Because modules are cached once per context this tool also makes it easy to isolate globals and state between tests running in the same process.

Installation

npm install context-require

Example

./index.js

import createRequire from "context-require";

const browserRequire = createRequire({
  dir: __dirname,
  context: new JSDOM('<div>Hello World</div>').window, // This object becomes the context for any required files.
  extensions: ..., // Same as require.extensions but only used in the above context.
  resolve(from, request, parentModule) {...} // Override file resolution for this context.
});

browserRequire("./get-document-body").innerHTML; // <div>Hello World</div>

./get-document-body.js

typeof global; // undefined
module.exports = document.body;

Contributions

  • Use npm test to build and run tests.

Please feel free to create a PR!

1.4.2

4 months ago

1.4.0

9 months ago

1.3.0

9 months ago

1.2.2

3 years ago

1.2.0

3 years ago

1.2.1

3 years ago

1.1.4

3 years ago

1.1.1

3 years ago

1.1.3

3 years ago

1.1.2

3 years ago

1.1.0

3 years ago

1.0.4

5 years ago

1.0.3

6 years ago

1.0.2

6 years ago

1.0.1

6 years ago

1.0.0

6 years ago