Require typescript file after ts-node.register doesn't work in ESM
Steps to reproduce the problem
index.mjs
import { dirname, resolve } from "path";
import { createRequire } from "module";
import tsnode from "ts-node";
const require = createRequire(import.meta.url);
const __dirname = dirname(decodeURI(new URL(import.meta.url).pathname)).replace(/^\/([A-Za-z]):\//, "$1:/");
tsnode.register({
project: resolve(__dirname, "tsconfig.json"),
});
(() => {
const res = require("./file.ts");
res.init();
})();
Actual Behavior
Uncaught exception: Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: ./file.ts require() of ES modules is not supported. require() of ./main.ts from ./index.mjs is an ES module file as it is a .ts file whose nearest parent package.json contains "type": "module" which defines all .ts files in that package scope as ES modules. Instead change the requiring code to use import(), or remove "type": "module" from ./package.json.
Expected Behavior
There are no such error if start file from cmd
node --loader ts-node/esm --inspect ./file.ts
Specifications
- ts-node version: v10.9.1
- node version: v16.19.0
- TypeScript version: v5.0.3
- tsconfig.json, if you're using one:
{
"compilerOptions": {
"outDir": "_dist",
"target": "ESNext",
"module": "ESNext",
"moduleResolution": "node16",
"esModuleInterop": true
},
"ts-node": {
"esm": true,
"transpileOnly": true
},
"include": ["."]
}
- package.json:
{
"type": "module"
}
- Operating system and version: Windows 10 22H2
- If Windows, are you using WSL or WSL2?: WSL2
I'm also getting this on Node 20.19.0. Which is very unfortunate given that require(ESM) is natively supported in that version.
Isolated minimum reproduction: https://github.com/JoshuaKGoldberg/repros/tree/ts-node-err-require-esm-node-20
Internally, it looks like ts-node is throwing its own error that intentionally matches its error code to the Node.js "ERR_REQUIRE_ESM" constant.