Fixes #4803: wrong error thrown if loader is used #4807
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Requirements
Description of the Change
When loading test files, there is a heuristic that tries to determine whether to
import
orrequire
them. This heuristic failed in the presence of a loader that recognizes filenames that are not.js/.mjs
. In this case, whenrequire
-ing the file, Node.js does not throwERR_REQUIRE_ESM
(because of the different extension) but rather aSyntaxError
saying that a CJSJ cannot useimport
.I added some more code to this heuristic to deal with the problem by checking if the error is the aforementioned syntax error, and if so, throw the original error.
Alternate Designs
Couldn't think of any.
Why should this be in core?
Well... this is the code of the loading mechanism in Mocha.
Benefits
Devs that use ESM with loaders will get the correct error and not a weird error that they can't use to understand what the problem is.
Possible Drawbacks
Heuristics, as they go, should be tampered with lightly, given that they may succeed in all our tests, but fail in the wild world out there.
I have been careful to add tests to all weird cases I've seen, so I'm pretty confident of the change, but as I said, this may be problematic.
Applicable issues
Not a breaking change.