Skip to content

Commit 5d23c98

Browse files
committedJan 11, 2024
feat(interopDefault): support preferNamespace
1 parent 14eb72d commit 5d23c98

File tree

3 files changed

+24
-7
lines changed

3 files changed

+24
-7
lines changed
 

‎README.md

+4
Original file line numberDiff line numberDiff line change
@@ -469,6 +469,10 @@ import myModule from "my-module";
469469
console.log(interopDefault(myModule));
470470
```
471471
472+
**Options:**
473+
474+
- `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)
475+
472476
### `sanitizeURIComponent`
473477
474478
Replace reserved characters from a segment of URI to make it compatible with [rfc2396](https://datatracker.ietf.org/doc/html/rfc2396).

‎src/cjs.ts

+5-2
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,10 @@ export function createCommonJS(url: string): CommonjsContext {
3131
} as CommonjsContext;
3232
}
3333

34-
export function interopDefault(sourceModule: any): any {
34+
export function interopDefault(
35+
sourceModule: any,
36+
opts: { preferNamespace?: boolean } = {},
37+
): any {
3538
if (!isObject(sourceModule) || !("default" in sourceModule)) {
3639
return sourceModule;
3740
}
@@ -40,7 +43,7 @@ export function interopDefault(sourceModule: any): any {
4043
return sourceModule;
4144
}
4245
if (typeof defaultValue !== "object") {
43-
return defaultValue;
46+
return opts.preferNamespace ? sourceModule : defaultValue;
4447
}
4548
for (const key in sourceModule) {
4649
if (key === "default") {

‎test/interop.test.ts

+15-5
Original file line numberDiff line numberDiff line change
@@ -24,16 +24,26 @@ const tests = [
2424
{ default: undefined, x: 1 },
2525
{ default: undefined, x: 1 },
2626
],
27-
];
27+
[{ default: "test", x: 123 }, "test"],
28+
[
29+
{ default: "test", x: 123 },
30+
{ default: "test", x: 123 },
31+
{ preferNamespace: true },
32+
],
33+
] as const;
2834

2935
describe("interopDefault", () => {
30-
for (const [input, result] of tests) {
36+
for (const [input, result, opts] of tests) {
3137
it(JSON.stringify(input), () => {
32-
const interop = interopDefault(input);
38+
const interop = interopDefault(input, opts);
3339
expect(interop).to.deep.equal(result);
34-
if (typeof input === "object" && "default" in input) {
40+
if (
41+
typeof input === "object" &&
42+
typeof result === "object" &&
43+
"default" in input
44+
) {
3545
expect(interop.default).to.deep.equal(
36-
"default" in (result as any) ? (result as any).default : result,
46+
"default" in result ? result.default : result,
3747
);
3848
} else {
3949
expect(interop).to.deep.equal(result);

0 commit comments

Comments
 (0)
Please sign in to comment.