Using TypeScript in Node.js project with "module": "commonjs"

41 views Asked by At

TypeScript documentation says:

Node.js’s rules for module format detection and interoperability make it incorrect to specify module as esnext or commonjs for projects that run in Node.js, even if all files emitted by tsc are ESM or CJS, respectively.

I'm trying to get full list of what exactly is incorrect and what are potential consequences. I tried to build simple hello world with "module": "commonjs" in my tsconfig.json and, except for the fact it is transpiled to quite unreadable code output, code is perfectly runnable by Node 20.

My tsconfig.json is:

{
  "compilerOptions": {
    "target": "esnext",
    "module": "commonjs",
    "outDir": "./dist",
    "skipLibCheck": true
  },
}

and then I have two files index.ts and module.ts:

index.ts:

import { car } from "./module"; console.log("car", car)

module.ts:

export const car = {
  brand: "Ford",
  model: "Fiesta",
};

I build it with tsc --build and I get properly built index.js and module.js, perfectly runnable by Node. This is obviously super simple but has module resolution and works. What has to be done to break things and see that having "module": "commonjs" is indeed incorrect as the documentation says?

0

There are 0 answers