Skip to content

Commit 14eb72d

Browse files
committedJan 11, 2024
fix(interopDefault): skip nullish values for default and explicitly return non-objects as-is
related to #194
1 parent 0d6b0b2 commit 14eb72d

File tree

2 files changed

+24
-8
lines changed

2 files changed

+24
-8
lines changed
 

‎src/cjs.ts

+13-7
Original file line numberDiff line numberDiff line change
@@ -35,24 +35,30 @@ export function interopDefault(sourceModule: any): any {
3535
if (!isObject(sourceModule) || !("default" in sourceModule)) {
3636
return sourceModule;
3737
}
38-
const newModule = sourceModule.default;
38+
const defaultValue = sourceModule.default;
39+
if (defaultValue === undefined || defaultValue === null) {
40+
return sourceModule;
41+
}
42+
if (typeof defaultValue !== "object") {
43+
return defaultValue;
44+
}
3945
for (const key in sourceModule) {
4046
if (key === "default") {
4147
try {
42-
if (!(key in newModule)) {
43-
Object.defineProperty(newModule, key, {
48+
if (!(key in defaultValue)) {
49+
Object.defineProperty(defaultValue, key, {
4450
enumerable: false,
4551
configurable: false,
4652
get() {
47-
return newModule;
53+
return defaultValue;
4854
},
4955
});
5056
}
5157
} catch {}
5258
} else {
5359
try {
54-
if (!(key in newModule)) {
55-
Object.defineProperty(newModule, key, {
60+
if (!(key in defaultValue)) {
61+
Object.defineProperty(defaultValue, key, {
5662
enumerable: true,
5763
configurable: true,
5864
get() {
@@ -63,5 +69,5 @@ export function interopDefault(sourceModule: any): any {
6369
} catch {}
6470
}
6571
}
66-
return newModule;
72+
return defaultValue;
6773
}

‎test/interop.test.ts

+11-1
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,14 @@ const tests = [
1616
{ named: 1, default: { x: 2 } },
1717
{ named: 1, x: 2 },
1818
],
19+
[
20+
{ default: null, x: 1 }, // eslint-disable-line unicorn/no-null
21+
{ default: null, x: 1 }, // eslint-disable-line unicorn/no-null
22+
],
23+
[
24+
{ default: undefined, x: 1 },
25+
{ default: undefined, x: 1 },
26+
],
1927
];
2028

2129
describe("interopDefault", () => {
@@ -24,7 +32,9 @@ describe("interopDefault", () => {
2432
const interop = interopDefault(input);
2533
expect(interop).to.deep.equal(result);
2634
if (typeof input === "object" && "default" in input) {
27-
expect(interop.default).to.deep.equal(result);
35+
expect(interop.default).to.deep.equal(
36+
"default" in (result as any) ? (result as any).default : result,
37+
);
2838
} else {
2939
expect(interop).to.deep.equal(result);
3040
}

0 commit comments

Comments
 (0)
Please sign in to comment.