Skip to content

Commit 2e90551

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 71dcfd7 commit 2e90551

File tree

1 file changed

+10
-0
lines changed

1 file changed

+10
-0
lines changed

esm.mjs

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

0 commit comments

Comments
 (0)