Skip to content
16 changes: 13 additions & 3 deletions lib/nodejs/esm-utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -92,9 +92,19 @@ const tryImportAndRequire = async (file, esmDecorator) => {
const requireModule = async (file, esmDecorator) => {
try {
return require(file);
} catch (err) {
// Import if require fails.
return dealWithExports(await formattedImport(file, esmDecorator));
} catch (requireErr) {
// Fallback to import() if require() fails.
try {
return dealWithExports(await formattedImport(file, esmDecorator));
} catch (importErr) {
// If a --require module throws in a Node.js version that doesn't yet support .ts files,
Comment thread
JoshuaKGoldberg marked this conversation as resolved.
Resolved
// the fallback import() will throw an uninformative error about the file extension.
// What we actually care about is the original require() error.
// See: https://github.com/mochajs/mocha/issues/5393
throw /\.(?:c|m)?ts$/.test(file) || importErr?.code === "ERR_UNKNOWN_FILE_EXTENSION"
Comment thread
JoshuaKGoldberg marked this conversation as resolved.
Resolved
? requireErr
: importErr;
}
}
}

Expand Down