Skip to content

Commit

Permalink
Allow passing the parent module in explicitly for setting the require…
Browse files Browse the repository at this point in the history
… context
  • Loading branch information
airhorns committed Apr 11, 2024
1 parent 81db81e commit 857750b
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 4 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "requirefire",
"version": "0.4.0",
"version": "0.4.1",
"author": "Harry Brundage",
"license": "MIT",
"repository": {
Expand Down
12 changes: 12 additions & 0 deletions spec/requirefire.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -110,4 +110,16 @@ describe("requirefire", () => {
expect(mod.main.key).toEqual("main");
expect(mod.sub.key).toEqual("sub");
});

test("instances can be passed the parent module for resolving relative paths", () => {
_require = requirefire(module);

const one = _require("./fixtures/mod_a");
for (const key of Object.keys(_require.cache)) {
delete _require.cache[key];
}
const two = _require("./fixtures/mod_a");
expect(one).not.toBe(two);
expect(one.name).toEqual(two.name);
})
});
11 changes: 8 additions & 3 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,8 +58,14 @@ const loadModuleWithWrapper = (module: Module, prefix: string, suffix: string) =

/**
* Produce a new requirefire instance.
*
* @param contextModule The module that will be used as the parent module for the requirefire instance. Relative paths will be resolved relative to this module.
*/
const createRequirefire = () => {
const createRequirefire = (contextModule?: Module) => {
if (!contextModule && module.parent) {
contextModule = module.parent;
}

const cache: Record<string, Module> = {};
const resolver = ResolverFactory.createResolver({
useSyncFileSystemCalls: true,
Expand Down Expand Up @@ -130,8 +136,7 @@ const createRequirefire = () => {
}

function requirefire(path: string) {
const requirier = module.parent ? module.parent : undefined;
return requireModule(path, requirier);
return requireModule(path, contextModule);
}

requireModule.cache = cache;
Expand Down

0 comments on commit 857750b

Please sign in to comment.