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 1 commit
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
37 changes: 32 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 @@ -435,10 +435,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 +475,28 @@ 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 cbResult.then(
jeysal marked this conversation as resolved.
Show resolved Hide resolved
() => {
revertHook();

return module;
},
error => {
revertHook();

return Promise.reject(error);
},
);
}
} finally {
revertHook();
Expand Down