Skip to content

Commit abb760a

Browse files
authored
feat: add sync way of requiring and transpiling module (#8808)
1 parent 0d48344 commit abb760a

File tree

1 file changed

+34
-5
lines changed

1 file changed

+34
-5
lines changed

packages/jest-transform/src/ScriptTransformer.ts

Lines changed: 34 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ import crypto from 'crypto';
99
import path from 'path';
1010
import vm from 'vm';
1111
import {Config} from '@jest/types';
12-
import {createDirectory} from 'jest-util';
12+
import {createDirectory, isPromise} from 'jest-util';
1313
import fs from 'graceful-fs';
1414
import {transformSync as babelTransform} from '@babel/core';
1515
// @ts-ignore: should just be `require.resolve`, but the tests mess that up
@@ -51,6 +51,17 @@ const projectCaches: WeakMap<
5151
// To reset the cache for specific changesets (rather than package version).
5252
const CACHE_VERSION = '1';
5353

54+
async function waitForPromiseWithCleanup(
55+
promise: Promise<any>,
56+
cleanup: () => void,
57+
) {
58+
try {
59+
await promise;
60+
} finally {
61+
cleanup();
62+
}
63+
}
64+
5465
export default class ScriptTransformer {
5566
static EVAL_RESULT_VARIABLE: 'Object.<anonymous>';
5667
private _cache: ProjectCache;
@@ -435,10 +446,18 @@ export default class ScriptTransformer {
435446
return fileSource;
436447
}
437448

438-
async requireAndTranspileModule<ModuleType = unknown>(
449+
requireAndTranspileModule<ModuleType = unknown>(
450+
moduleName: string,
451+
callback?: (module: ModuleType) => void,
452+
): ModuleType;
453+
requireAndTranspileModule<ModuleType = unknown>(
454+
moduleName: string,
455+
callback?: (module: ModuleType) => Promise<void>,
456+
): Promise<ModuleType>;
457+
requireAndTranspileModule<ModuleType = unknown>(
439458
moduleName: string,
440459
callback?: (module: ModuleType) => void | Promise<void>,
441-
): Promise<ModuleType> {
460+
): ModuleType | Promise<ModuleType> {
442461
// Load the transformer to avoid a cycle where we need to load a
443462
// transformer in order to transform it in the require hooks
444463
this.preloadTransformer(moduleName);
@@ -467,9 +486,19 @@ export default class ScriptTransformer {
467486
);
468487
const module: ModuleType = require(moduleName);
469488

489+
if (!callback) {
490+
revertHook();
491+
492+
return module;
493+
}
494+
470495
try {
471-
if (callback) {
472-
await callback(module);
496+
const cbResult = callback(module);
497+
498+
if (isPromise(cbResult)) {
499+
return waitForPromiseWithCleanup(cbResult, revertHook).then(
500+
() => module,
501+
);
473502
}
474503
} finally {
475504
revertHook();

0 commit comments

Comments
 (0)