Skip to content

Commit

Permalink
refactor(interopDefault): simplify logic for default export checks (#322
Browse files Browse the repository at this point in the history
)
  • Loading branch information
pi0 authored Oct 5, 2024
1 parent 4be8bff commit fd5d7ea
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 21 deletions.
25 changes: 8 additions & 17 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,18 +108,9 @@ function interopDefault(mod: any): any {
return mod;
}

const defaultExport = mod.default;
if (defaultExport === undefined || defaultExport === null) {
return mod;
}

const modKeys = Object.getOwnPropertyNames(mod);
if (modKeys.length === 1 || (modKeys.length === 2 && "__esModule" in mod)) {
return defaultExport;
}

const defaultExportType = typeof defaultExport;
if (defaultExportType !== "object" && defaultExportType !== "function") {
const def = mod.default;
const defType = typeof def;
if (def === null || (defType !== "object" && defType !== "function")) {
return mod;
}

Expand All @@ -129,23 +120,23 @@ function interopDefault(mod: any): any {
return true;
}
if (prop === "default") {
return defaultExport;
return def;
}
if (Reflect.has(target, prop)) {
return Reflect.get(target, prop, receiver);
}
let fallback = Reflect.get(defaultExport, prop, receiver);
let fallback = Reflect.get(def, prop, receiver);
if (typeof fallback === "function") {
fallback = fallback.bind(defaultExport);
fallback = fallback.bind(def);
}
return fallback;
},
apply(target, thisArg, args) {
if (typeof target === "function") {
return Reflect.apply(target, thisArg, args);
}
if (defaultExportType === "function") {
return Reflect.apply(defaultExport, thisArg, args);
if (defType === "function") {
return Reflect.apply(def, thisArg, args);
}
},
});
Expand Down
8 changes: 4 additions & 4 deletions test/bun.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,10 +47,10 @@ test("hmr", async () => {
let value;

await writeFile(tmpFile, "export default 1");
value = _jiti(tmpFile);
expect(value).toBe(1);
value = (await _jiti.import(tmpFile)) as any;
expect(value.default).toBe(1);

await writeFile(tmpFile, "export default 2");
value = _jiti(tmpFile);
expect(value).toBe(2);
value = (await _jiti.import(tmpFile)) as any;
expect(value.default).toBe(2);
});

0 comments on commit fd5d7ea

Please # to comment.