Skip to content

Commit

Permalink
feat: add sync way of requiring and transpiling module (#8808)
Browse files Browse the repository at this point in the history
  • Loading branch information
SimenB authored Aug 14, 2019
1 parent 0d48344 commit abb760a
Showing 1 changed file with 34 additions and 5 deletions.
39 changes: 34 additions & 5 deletions packages/jest-transform/src/ScriptTransformer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import crypto from 'crypto';
import path from 'path';
import vm from 'vm';
import {Config} from '@jest/types';
import {createDirectory} from 'jest-util';
import {createDirectory, isPromise} from 'jest-util';
import fs from 'graceful-fs';
import {transformSync as babelTransform} from '@babel/core';
// @ts-ignore: should just be `require.resolve`, but the tests mess that up
Expand Down Expand Up @@ -51,6 +51,17 @@ const projectCaches: WeakMap<
// To reset the cache for specific changesets (rather than package version).
const CACHE_VERSION = '1';

async function waitForPromiseWithCleanup(
promise: Promise<any>,
cleanup: () => void,
) {
try {
await promise;
} finally {
cleanup();
}
}

export default class ScriptTransformer {
static EVAL_RESULT_VARIABLE: 'Object.<anonymous>';
private _cache: ProjectCache;
Expand Down Expand Up @@ -435,10 +446,18 @@ export default class ScriptTransformer {
return fileSource;
}

async requireAndTranspileModule<ModuleType = unknown>(
requireAndTranspileModule<ModuleType = unknown>(
moduleName: string,
callback?: (module: ModuleType) => void,
): ModuleType;
requireAndTranspileModule<ModuleType = unknown>(
moduleName: string,
callback?: (module: ModuleType) => Promise<void>,
): Promise<ModuleType>;
requireAndTranspileModule<ModuleType = unknown>(
moduleName: string,
callback?: (module: ModuleType) => void | Promise<void>,
): Promise<ModuleType> {
): ModuleType | Promise<ModuleType> {
// Load the transformer to avoid a cycle where we need to load a
// transformer in order to transform it in the require hooks
this.preloadTransformer(moduleName);
Expand Down Expand Up @@ -467,9 +486,19 @@ export default class ScriptTransformer {
);
const module: ModuleType = require(moduleName);

if (!callback) {
revertHook();

return module;
}

try {
if (callback) {
await callback(module);
const cbResult = callback(module);

if (isPromise(cbResult)) {
return waitForPromiseWithCleanup(cbResult, revertHook).then(
() => module,
);
}
} finally {
revertHook();
Expand Down

0 comments on commit abb760a

Please sign in to comment.