Search code examples
node.jstypescriptes6-modules

How to use ESM and TypeScript in Node.js with test coverage


I'm trying to use ESM and TypeScript in Node.js v14. This is not hard and exist some questions for it:

Try to summarize it in tsconfig.json:

{
  "compilerOptions": {
    "module": "es2022",
    "esModuleInterop": true
  },
  "ts-node": {
    "esm": true
  }
}

If not provide esm: true, you can use ts-node-esm instead of ts-node

For example: npx ts-node-esm my-code.ts

But main problem is that when using nyc, it can't correctly collect the statements/branches that have passed.

I have tried nyc-config-typescript and esm-loader-hook but none of these works.

How can I handle this problems?


Solution

  • I have tried to tackle this problem two days and finally "fix" it by using c8

    You can see the example by example repo. In the example, I'm using jasmine but you can use other testing framework (e.g. mocha) as you want.

    Finally you can execute testing with coverage by:

    npx c8 ts-node jasmine.ts