To summarize, import-in-the-middle can cause problems in the following situation:
A Node core module (node:*) is imported
Another loader is added before import-in-the-middle
That loader tries to resolve files that don't exist on disk
In practice, this occurs when using import-in-the-middle with code that's being executed with tsx. tsx will try to resolve .js files by also looking for the same file path but with a .ts extension. In many cases, including the synthetic code that import-in-the-middle generates to import lib/register.js, such a corresponding .ts file does not exist.
The actual error arises from Node, which assumes that parentURL will always be a file:// URL when constructing an ERR_MODULE_NOT_FOUND error; see the linked issue above. In the above scenario, the .ts file that is being resolved does not exist, so such an error is created, and parentURL === 'node:*', so the failing case is triggered. It seems like Node is receptive to changing that behavior, but in the meantime, I was hoping to land this patch so that one doesn't have to wait for and upgrade to a new version of Node.
The fix works by short-circuiting the resolution of lib/register.js so that the other loader (that tries to resolve non-existent paths) is never tried.
This PR fixes the issue that's been described at length in the following issues:
To summarize,
import-in-the-middle
can cause problems in the following situation:node:*
) is importedimport-in-the-middle
In practice, this occurs when using
import-in-the-middle
with code that's being executed withtsx
.tsx
will try to resolve.js
files by also looking for the same file path but with a.ts
extension. In many cases, including the synthetic code thatimport-in-the-middle
generates to importlib/register.js
, such a corresponding.ts
file does not exist.The actual error arises from Node, which assumes that
parentURL
will always be afile://
URL when constructing anERR_MODULE_NOT_FOUND
error; see the linked issue above. In the above scenario, the.ts
file that is being resolved does not exist, so such an error is created, andparentURL === 'node:*'
, so the failing case is triggered. It seems like Node is receptive to changing that behavior, but in the meantime, I was hoping to land this patch so that one doesn't have to wait for and upgrade to a new version of Node.The fix works by short-circuiting the resolution of
lib/register.js
so that the other loader (that tries to resolve non-existent paths) is never tried.