Подписаться на блог

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.

  1. Update package.json to define modules system
"type": "module",
  1. 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
  }
}
  1. 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
  1. Enjoy!
1 комментарий
Не тупа пахан 2022

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]