Why does Typescript allows "import" in CommonJS modules?

59 Views Asked by At

I am trying to get a handle on Typescript's module system, but even after reading carefully the documentation, I couldn't understand the following behavior :

Setup

Child.ts

export const child = "Child";

Parent.ts

import { child } from "./Child";
console.log(child);

tsconfig.json

"compilerOptions": {
  "module": "node16",
  "esModuleInterop": true, // No impact whether true of false

and my package.json doesn't have "type":"module"

Question

After reading Typescript's Module format detection, I expected that : since I don't have "type":"module" in my package.json, TypeScript would treat my Parent.ts and Child.ts as CommonJS modules, thus Typescript should give me an error on import and advice me to use require().

However, this is not the case. Typescript is allowing me to use import in a CommonJS file.

What did I miss? Is there a config in my tsconfig.json that causes this? Thank you for your help

Edit Maybe Typescript natively allow ESM modules for its own .ts files and module resolution. However, I undertand that ESM modules requires the extension for relative paths. If true, Typescript should throw an error for import { child } from "./Child"; and require import { child } from "./Child.ts";. But this is not the case

0

There are 0 best solutions below