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鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add sync way of requiring and transpiling module #8808

Merged
merged 2 commits into from Aug 14, 2019
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
39 changes: 34 additions & 5 deletions packages/jest-transform/src/ScriptTransformer.ts
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