Skip to content

Commit

Permalink
feat(interopDefault): support preferNamespace
Browse files Browse the repository at this point in the history
  • Loading branch information
pi0 committed Jan 11, 2024
1 parent 14eb72d commit 5d23c98
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 7 deletions.
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand Down
7 changes: 5 additions & 2 deletions src/cjs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand All @@ -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") {
Expand Down
20 changes: 15 additions & 5 deletions test/interop.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down

0 comments on commit 5d23c98

Please sign in to comment.