Skip to content

🐛 Bug: esm-utils.js#requireModule() masks more helpful requireErr in some cases #5792

@trentm

Description

@trentm

Bug Report Checklist

Expected

If esm-utils.js cannot know for sure if a require() or import() error is most relevant, perhaps both should be shown to the user with context?

Actual

When using ts-node for test files (e.g. with "require": ["ts-node/register/transpile-only"], in .mocharc.json), a tsconfig.json that specifies CommonJS, and a Node.js version that does type-stripping by default (Node.js 22 and later),
then any accidental case that results in the require('./test/something.test.ts') throwing an error,
will result in mocha's esm-utils.js#requireModule() attempting to import(...) the test file.

If the import(...) also fails, then the importErr is (often) reported and the requireErr is not shown.

There is some guessing trying to decide which of importErr or requireErr to show.
opentelemetry-js-contrib.git another case where requireErr is more relevant, but importErr is shown.
The full case is described here: open-telemetry/opentelemetry-js-contrib#3418 (comment)

I made a smaller repro here: https://github.com/trentm/repro-mocha-unsupported-dir-import

Minimal, Complete and Verifiable Example

https://github.com/trentm/repro-mocha-unsupported-dir-import

Versions

% npx mocha --version
11.7.5
% node --version
v24.14.0

The combination here requires:

  • a mocha which includes feat: use require to load esm #5366
  • Node.js that supports require(esm), Node.js 20 and later.
  • Node.js that does type-stripping by default, Node.js 22 and later.

Additional Info

I suppose a specific exclude for importErr.code === 'ERR_UNSUPPORTED_DIR_IMPORT' could be added to requireModule(), but I'm not sure if that completes the set of import() error codes that suggest "oops, this was likely a CommonJS file that we tried to import()".

Metadata

Metadata

Assignees

Labels

status: accepting prsMocha can use your help with this one!type: buga defect, confirmed by a maintainer

Type

No type

Projects

Status

No status

Relationships

None yet

Development

No branches or pull requests

Issue actions