Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor(interopDefault): simplify logic for default export checks #322

Merged
merged 2 commits into from
Oct 5, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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);
});