How to run TS-node with ES modules and CommonJS?
If you’ve got ERR_REQUIRE_ESM, ERR_UNKNOWN_FILE_EXTENSION for TS files, ERR_MODULE_NOT_FOUND for TS files with ES modules and other errors related to «CJS to ESM migration problem» in your NodeJS project you can fix it by following these steps.
- Update package.json to define modules system
"type": "module",
- Update tsconfig.json to support ESM in TS-node
{
"compilerOptions": {
"target": "esnext",
"emitDecoratorMetadata": true,
"module": "esnext",
"moduleResolution": "node",
"types": ["node"],
"resolveJsonModule": true,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true
}
}
- Run your entry point script using node and ts-node as node loader
node --experimental-specifier-resolution=node --loader ts-node/esm src/index.ts
- Enjoy!
Wow, that’s amazing! Thank you for this tutorial 👏[write a good comment and I’ll give you $10, don’t forget to delete this before posting]