diff --git a/README.md b/README.md index a797050..f50195e 100644 --- a/README.md +++ b/README.md @@ -469,6 +469,10 @@ import myModule from "my-module"; console.log(interopDefault(myModule)); ``` +**Options:** + +- `preferNamespace`: In case that `default` value exists but is not extendable (when is string for example), return input as-is (default is `false`, meaning `default`'s value is prefered even if cannot be extended) + ### `sanitizeURIComponent` Replace reserved characters from a segment of URI to make it compatible with [rfc2396](https://datatracker.ietf.org/doc/html/rfc2396). diff --git a/src/cjs.ts b/src/cjs.ts index eb2432b..ea56997 100644 --- a/src/cjs.ts +++ b/src/cjs.ts @@ -31,7 +31,10 @@ export function createCommonJS(url: string): CommonjsContext { } as CommonjsContext; } -export function interopDefault(sourceModule: any): any { +export function interopDefault( + sourceModule: any, + opts: { preferNamespace?: boolean } = {}, +): any { if (!isObject(sourceModule) || !("default" in sourceModule)) { return sourceModule; } @@ -40,7 +43,7 @@ export function interopDefault(sourceModule: any): any { return sourceModule; } if (typeof defaultValue !== "object") { - return defaultValue; + return opts.preferNamespace ? sourceModule : defaultValue; } for (const key in sourceModule) { if (key === "default") { diff --git a/test/interop.test.ts b/test/interop.test.ts index 64f9f0c..913bc7a 100644 --- a/test/interop.test.ts +++ b/test/interop.test.ts @@ -24,16 +24,26 @@ const tests = [ { default: undefined, x: 1 }, { default: undefined, x: 1 }, ], -]; + [{ default: "test", x: 123 }, "test"], + [ + { default: "test", x: 123 }, + { default: "test", x: 123 }, + { preferNamespace: true }, + ], +] as const; describe("interopDefault", () => { - for (const [input, result] of tests) { + for (const [input, result, opts] of tests) { it(JSON.stringify(input), () => { - const interop = interopDefault(input); + const interop = interopDefault(input, opts); expect(interop).to.deep.equal(result); - if (typeof input === "object" && "default" in input) { + if ( + typeof input === "object" && + typeof result === "object" && + "default" in input + ) { expect(interop.default).to.deep.equal( - "default" in (result as any) ? (result as any).default : result, + "default" in result ? result.default : result, ); } else { expect(interop).to.deep.equal(result);