Skip to content

Commit

Permalink
feat(jest): optionally jest transform esm files to cjs
Browse files Browse the repository at this point in the history
  • Loading branch information
adamdbradley committed Oct 29, 2019
1 parent a6c0fd3 commit 7adf62f
Showing 1 changed file with 23 additions and 3 deletions.
26 changes: 23 additions & 3 deletions src/testing/jest/jest-preprocessor.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { formatDiagnostic, getCompilerOptions, transpile } from '../test-transpile';
// import { basename } from 'path';


export const jestPreprocessor = {
Expand All @@ -10,7 +9,7 @@ export const jestPreprocessor = {
return '';
}

if (filePath.endsWith('.ts') || filePath.endsWith('.tsx') || filePath.endsWith('.jsx')) {
if (shouldTransformTS(filePath) || shouldTransformESM(filePath, sourceText)) {
const opts = Object.assign({}, this.getCompilerOptions(jestConfig.rootDir));

const results = transpile(sourceText, opts, filePath);
Expand Down Expand Up @@ -59,6 +58,27 @@ export const jestPreprocessor = {
!!transformOptions.instrument
];

return key.join(':') + Math.random();
return key.join(':');
}
};

function shouldTransformTS(filePath: string) {
return (filePath.endsWith('.ts') || filePath.endsWith('.tsx') || filePath.endsWith('.jsx'));
}

function shouldTransformESM(filePath: string, sourceText: string) {
// there may be false positives here
// but worst case scenario a commonjs file is transpiled to commonjs
if (filePath.endsWith('.esm.js') || filePath.endsWith('.mjs')) {
return true;
}
if (filePath.endsWith('.js')) {
if (sourceText.includes('import ') || sourceText.includes('import.') || sourceText.includes('import(')) {
return true;
}
if (sourceText.includes('export ')) {
return true;
}
}
return false;
}

0 comments on commit 7adf62f

Please sign in to comment.