ESM considerations for ts-node and other require.extensions hooks #4274
Labels
stale
this has been inactive for a while...
type: discussion
debates, philosophy, navel-gazing, etc.
type: question
support question
I want to share a couple things I've hit while adding ESM support to ts-node, because I think it affects design decisions for mocha's ESM support.
require.extensions
need to add hacks to classify files as either CJS or ESM@emma-borhanian hit an issue with babel's
require.extensions
hook, which also happens to ts-node#4038 (comment)
I've shared the fix I'm going to add to ts-node; babel could do something similar.
nodejs/modules#351 (comment)
With this fix we will throw the same errors as node when you try to
require()
an ESM file.Mocha needs to consult
require.extensions
to properly load non-standard file extensionsIn mocha you have a comment about using
import()
for all files in the future, letting it classify files as CJS or ESM. Unfortunately, I believe this will fail to resolve non-standard file extensions such as.ts
.In ts-node we have implemented an ESM loader that does understand
.ts
,.tsx
, and.jsx
. However, this requires users to invoke node or mocha like this:Users who are not using ESM will not install this loader, so the ESM resolver will not be able to resolve nor classify
.ts
,.tsx
, or.jsx
files. For this,mocha
must continue usingrequire
to locate and attempt loading the file. I believe that evenimport(require.resolve('./ts-file.ts'))
will fail to classify the file as CJS or ESM if our custom ESM hook is not installed.See also: nodejs/node#33226
It's possible that node's built-in loader will be changed to classify unrecognized extensions based on package.json "type" field, but I'm not sure.
I hope this information is helpful!
The text was updated successfully, but these errors were encountered: