开发者

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:

  • How to use ts-node ESM with node modules?
  • Can't run my Node.js Typescript project TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" for /app/src/App.ts

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 开发者_如何学JAVAhave tried nyc-config-typescript and esm-loader-hook but none of these works.

How can I handle this problems?


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜