Skip to content

Commit 6e1e66c

Browse files
committed
fix: Add globalPreload to ts-node/esm for node 20
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.
1 parent 7af5c48 commit 6e1e66c

File tree

1 file changed

+10
-0
lines changed

1 file changed

+10
-0
lines changed

esm.mjs

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,3 +5,13 @@ const require = createRequire(fileURLToPath(import.meta.url));
55
/** @type {import('./dist/esm')} */
66
const esm = require('./dist/esm');
77
export const { resolve, load, getFormat, transformSource } = esm.registerAndCreateEsmHooks();
8+
9+
// Affordance for node 20, where load() happens in an isolated thread
10+
export const globalPreload = () => {
11+
const self = fileURLToPath(import.meta.url);
12+
return `
13+
const { createRequire } = getBuiltin('module');
14+
const require = createRequire(${JSON.stringify(self)});
15+
require('./dist/esm').registerAndCreateEsmHooks();
16+
`;
17+
};

0 commit comments

Comments
 (0)