Skip to content

Commit

Permalink
fix: use inline require cache to avoid circular dependencies (#125)
Browse files Browse the repository at this point in the history
  • Loading branch information
pi0 authored Mar 6, 2023
1 parent e947bec commit 55b9935
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 3 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
"build": "pnpm clean && cross-env NODE_ENV=production pnpm webpack",
"clean": "rm -rf dist",
"dev": "pnpm clean && pnpm webpack --watch",
"jiti": "cross-env JITI_DEBUG=1 JITI_CACHE=false ./bin/jiti.js",
"jiti": "cross-env JITI_DEBUG=1 JITI_CACHE=false JITI_REQUIRE_CACHE=false ./bin/jiti.js",
"jiti:legacy": "cross-env JITI_DEBUG=1 npx node@12 ./bin/jiti.js",
"lint": "eslint --ext .ts,.js . && prettier -c src lib test stubs",
"release": "pnpm build && pnpm test && changelogen --release && npm publish && git push --follow-tags",
Expand Down
16 changes: 14 additions & 2 deletions src/jiti.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,8 @@ export interface JITI extends Require {
export default function createJITI(
_filename: string,
opts: JITIOptions = {},
parentModule?: typeof module
parentModule?: typeof module,
requiredModules?: Record<string, typeof module>
): JITI {
opts = { ...defaults, ...opts };

Expand Down Expand Up @@ -291,6 +292,9 @@ export default function createJITI(
}

// Check for CJS cache
if (requiredModules && requiredModules[filename]) {
return _interopDefault(requiredModules[filename]?.exports);
}
if (opts.requireCache && nativeRequire.cache[filename]) {
return _interopDefault(nativeRequire.cache[filename]?.exports);
}
Expand Down Expand Up @@ -344,7 +348,7 @@ export default function createJITI(
parentModule.children.push(mod);
}
}
mod.require = createJITI(filename, opts, mod);
mod.require = createJITI(filename, opts, mod, requiredModules || {});

// @ts-ignore
mod.path = dirname(filename);
Expand All @@ -353,6 +357,9 @@ export default function createJITI(
mod.paths = Module._nodeModulePaths(mod.path);

// Set CJS cache before eval
if (requiredModules) {
requiredModules[filename] = mod;
}
if (opts.requireCache) {
nativeRequire.cache[filename] = mod;
}
Expand Down Expand Up @@ -390,6 +397,11 @@ export default function createJITI(
opts.onError!(error);
}

// Remove from required modules cache
if (requiredModules) {
delete requiredModules[filename];
}

// Check for parse errors
if (mod.exports && mod.exports.__JITI_ERROR__) {
const { filename, line, column, code, message } =
Expand Down

0 comments on commit 55b9935

Please sign in to comment.