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’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(jest-util): add requireOrImportModule util for importing CJS or ESM #11199

Merged
merged 8 commits into from Mar 16, 2021
30 changes: 3 additions & 27 deletions packages/jest-config/src/readConfigFileAndSetRootDir.ts
Expand Up @@ -6,11 +6,10 @@
*/

import * as path from 'path';
import {pathToFileURL} from 'url';
import * as fs from 'graceful-fs';
import type {Register} from 'ts-node';
import type {Config} from '@jest/types';
import {interopRequireDefault} from 'jest-util';
import {interopRequireDefault, requireOrImportModule} from 'jest-util';
import {
JEST_CONFIG_EXT_JSON,
JEST_CONFIG_EXT_TS,
Expand All @@ -35,33 +34,10 @@ export default async function readConfigFileAndSetRootDir(
if (isTS) {
configObject = await loadTSConfigFile(configPath);
} else {
configObject = require(configPath);
configObject = await requireOrImportModule<any>(configPath);
}
} catch (error) {
if (error.code === 'ERR_REQUIRE_ESM') {
try {
const configUrl = pathToFileURL(configPath);

// node `import()` supports URL, but TypeScript doesn't know that
const importedConfig = await import(configUrl.href);

if (!importedConfig.default) {
throw new Error(
`Jest: Failed to load mjs config file ${configPath} - did you use a default export?`,
);
}

configObject = importedConfig.default;
} catch (innerError) {
if (innerError.message === 'Not supported') {
throw new Error(
`Jest: Your version of Node does not support dynamic import - please enable it or use a .cjs file extension for file ${configPath}`,
);
}
Comment on lines -56 to -60
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All LTS Node should support dynamic import after Node 10 EOL.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yep. Jest 27 will support Node 10, but 28 will drop it

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

so we should keep the warning for now


throw innerError;
}
} else if (isJSON) {
if (isJSON) {
throw new Error(
`Jest: Failed to parse config file ${configPath}\n` +
` ${jsonlint.errors(fs.readFileSync(configPath, 'utf8'))}`,
Expand Down