diff --git a/README.md b/README.md index 74db733..381d6a0 100644 --- a/README.md +++ b/README.md @@ -20,7 +20,7 @@ npm i import-without-cache ## Usage ```ts -import { init, isSupported } from 'import-without-cache' +import { clearCJSCache, init, isSupported } from 'import-without-cache' if (!isSupported) { throw new Error('import-without-cache is not supported in this environment.') @@ -29,17 +29,21 @@ if (!isSupported) { const deregister = init() const mod = await import('some-module', { with: { cache: 'no' } }) + +clearCJSCache() // Optional: clear CommonJS cache if needed + // or const mod2 = await import(`no-cache://some-module`) +expect(mod).not.toBe(mod2) // Different instances + deregister() // Optional: deregister the hooks when no longer needed ``` ## Known Limitations - Support Node.js since v22.15.0, and doesn't support Deno or Bun. -- Only supports ESM modules. - - CommonJS cache can be cleared by `delete require.cache[require.resolve('module-name')]`. +- Only supports ESM modules by default. CommonJS cache can be cleared by `clearCJSCache`. - `require(esm)` is not supported. ## Sponsors diff --git a/src/index.ts b/src/index.ts index 4e7eeb4..adc3877 100644 --- a/src/index.ts +++ b/src/index.ts @@ -53,6 +53,12 @@ export function init(): () => void { }) } +export function clearCJSCache(): void { + for (const key of Object.keys(require.cache)) { + delete require.cache[key] + } +} + function getParentUUID(parentURL: string | undefined) { if (!parentURL) return return new URL(parentURL).searchParams.get('no-cache') ?? undefined diff --git a/tests/index.test.js b/tests/index.test.js index f26ad24..53f61d4 100644 --- a/tests/index.test.js +++ b/tests/index.test.js @@ -1,17 +1,8 @@ // @ts-check import assert from 'node:assert' -import { createRequire } from 'node:module' import { test } from 'node:test' -import { init } from '../dist/index.mjs' - -const require = createRequire(import.meta.url) - -function clearCJSCache() { - for (const key of Object.keys(require.cache)) { - delete require.cache[key] - } -} +import { clearCJSCache, init } from '../dist/index.mjs' test('import attributes', async () => { const deregister = init()