Skip to content

Commit

Permalink
fix: Add globalPreload to ts-node/esm for node 20
Browse files Browse the repository at this point in the history
As of node v20, loader hooks are executed in a separate isolated thread
environment.  As a result, they are unable to register the
`require.extensions` hooks in a way that would (in other node versions)
make both CJS and ESM work as expected.

By adding a `globalPreload` method, which *does* execute in the main
script environment (but with very limited capabilities), these hooks can
be attached properly, and `--loader=ts-node/esm` will once again make
both cjs and esm typescript programs work properly.
  • Loading branch information
isaacs committed May 6, 2023
1 parent 71dcfd7 commit 92c3ce3
Showing 1 changed file with 10 additions and 0 deletions.
10 changes: 10 additions & 0 deletions esm.mjs
Expand Up @@ -6,3 +6,13 @@ const require = createRequire(fileURLToPath(import.meta.url));
const esm = require('./dist/esm');
export const { resolve, load, getFormat, transformSource } =
esm.registerAndCreateEsmHooks();

// Affordance for node 20, where load() happens in an isolated thread
export const globalPreload = () => {
const self = fileURLToPath(import.meta.url);
return `
const { createRequire } = getBuiltin('module');
const require = createRequire(${JSON.stringify(self)});
require('./dist/esm').registerAndCreateEsmHooks();
`;
};

0 comments on commit 92c3ce3

Please sign in to comment.