diff --git a/package.json b/package.json index 488af7e8..37e1bd20 100644 --- a/package.json +++ b/package.json @@ -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", diff --git a/src/jiti.ts b/src/jiti.ts index 1d655f70..ece593e1 100644 --- a/src/jiti.ts +++ b/src/jiti.ts @@ -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 ): JITI { opts = { ...defaults, ...opts }; @@ -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); } @@ -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); @@ -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; } @@ -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 } =