Skip to content

Commit 650cc6c

Browse files
authored
fix(eval): fallback in async mode (#325)
1 parent c469748 commit 650cc6c

File tree

2 files changed

+34
-23
lines changed

2 files changed

+34
-23
lines changed

lib/types.d.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -223,6 +223,7 @@ export type EvalModuleOptions = Partial<{
223223
ext: string;
224224
cache: ModuleCache;
225225
async: boolean;
226+
forceTranspile: boolean;
226227
}>;
227228

228229
export interface TransformOptions {

src/eval.ts

Lines changed: 33 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -38,12 +38,11 @@ export function evalModule(
3838
(ext === ".js" && readNearestPackageJSON(filename)?.type === "module");
3939
const isCommonJS = ext === ".cjs";
4040
const needsTranspile =
41-
!isCommonJS && // CommonJS skips transpile
42-
!(isESM && evalOptions.async) && // In async mode, we can skip native ESM as well
43-
(isTypescript ||
44-
isESM ||
45-
ctx.isTransformRe.test(filename) ||
46-
hasESMSyntax(source));
41+
evalOptions.forceTranspile ??
42+
(!isCommonJS && // CommonJS skips transpile
43+
!(isESM && evalOptions.async) && // In async mode, we can skip native ESM as well
44+
// prettier-ignore
45+
(isTypescript || isESM || ctx.isTransformRe.test(filename) || hasESMSyntax(source)));
4746
const start = performance.now();
4847
if (needsTranspile) {
4948
source = transform(ctx, {
@@ -62,24 +61,35 @@ export function evalModule(
6261
`(${time}ms)`,
6362
);
6463
} else {
65-
try {
66-
debug(
67-
ctx,
68-
"[native]",
69-
evalOptions.async ? "[import]" : "[require]",
70-
filename,
71-
);
72-
return nativeImportOrRequire(ctx, filename, evalOptions.async);
73-
} catch (error: any) {
74-
debug(ctx, "Native require error:", error);
75-
debug(ctx, "[fallback]", filename);
76-
source = transform(ctx, {
77-
filename,
78-
source,
79-
ts: isTypescript,
80-
async: evalOptions.async ?? false,
81-
jsx: ctx.opts.jsx,
64+
debug(
65+
ctx,
66+
"[native]",
67+
evalOptions.async ? "[import]" : "[require]",
68+
filename,
69+
);
70+
71+
if (evalOptions.async) {
72+
return Promise.resolve(
73+
nativeImportOrRequire(ctx, filename, evalOptions.async),
74+
).catch((error: any) => {
75+
debug(ctx, "Native import error:", error);
76+
debug(ctx, "[fallback]", filename);
77+
evalModule(ctx, source, { ...evalOptions, forceTranspile: true });
8278
});
79+
} else {
80+
try {
81+
return nativeImportOrRequire(ctx, filename, evalOptions.async);
82+
} catch (error: any) {
83+
debug(ctx, "Native require error:", error);
84+
debug(ctx, "[fallback]", filename);
85+
source = transform(ctx, {
86+
filename,
87+
source,
88+
ts: isTypescript,
89+
async: evalOptions.async ?? false,
90+
jsx: ctx.opts.jsx,
91+
});
92+
}
8393
}
8494
}
8595

0 commit comments

Comments
 (0)