Skip to content

Commit 7aa365b

Browse files
authored
fix(cjs-interop): handle function default exports (#396)
1 parent f9d67d2 commit 7aa365b

File tree

4 files changed

+34
-1
lines changed

4 files changed

+34
-1
lines changed

src/utils.ts

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -124,7 +124,13 @@ function interopDefault(mod: any): any {
124124
return true;
125125
}
126126
if (prop === "default") {
127-
return defIsNil ? mod : def;
127+
if (defIsNil) {
128+
return mod;
129+
}
130+
if (typeof def?.default === "function" && mod.__esModule) {
131+
return def.default; // #396
132+
}
133+
return def;
128134
}
129135
if (Reflect.has(target, prop)) {
130136
return Reflect.get(target, prop, receiver);

test/__snapshots__/fixtures.test.ts.snap

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@ exports[`fixtures > async > stdout 1`] = `"works"`;
44

55
exports[`fixtures > circular > stdout 1`] = `"a b c"`;
66

7+
exports[`fixtures > cjs-interop > stdout 1`] = `"CJS function default interop test passed"`;
8+
79
exports[`fixtures > data-uri > stdout 1`] = `""`;
810

911
exports[`fixtures > deps > stdout 1`] = `
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
module.exports = {
2+
__esModule: true,
3+
default: function myPlugin() {
4+
return "ok";
5+
},
6+
};
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
const { createJiti } = require("../../../lib/jiti.cjs");
2+
const path = require("node:path");
3+
4+
async function main() {
5+
const jiti = createJiti(__filename);
6+
const modPath = path.resolve(__dirname, "./function-default.cjs");
7+
8+
const loaded = await jiti.import(modPath, { default: true });
9+
10+
if (typeof loaded === "function") {
11+
console.log("CJS function default interop test passed");
12+
} else {
13+
console.log("CJS function default interop test failed");
14+
}
15+
}
16+
17+
main().catch((error_) => {
18+
console.error("Error:", error_);
19+
});

0 commit comments

Comments
 (0)