Typescript error with module/moduleResolution: "Node16" in CommonJS projects

Author: sydonia86Created Nov 29, 2024Updated Dec 1, 2024

This has been reported before (#1200) and marked as fixed, but unfortunately it's still not working in CommonJS projects. Typescript throws this error when compiling:

index.ts:1:25 - error TS1479: The current file is a CommonJS module whose imports will produce 'require' calls; however, the referenced file is an ECMAScript module and cannot be imported with 'require'. Consider writing a dynamic 'import("superstruct")' call instead.

Minimal repro

package.json

json
{
  "name": "repro",
  "version": "1.0.0",
  "license": "MIT",
  "devDependencies": {
    "typescript": "5.7.2"
  },
  "dependencies": {
    "superstruct": "2.0.2"
  }
}

tsconfig.json

json
{
  "compilerOptions": {
    "module": "Node16",
  }
}

index.ts

typescript
import superstruct from 'superstruct';

Solution

From looking at other packages and skimming through the typescript docs, it looks like the way to fix this is to replace the index.d.ts file with a pair of index.d.mts and index.d.cts files. How you'd generate the latter is a bit unclear. unbuild seems to be able to do so, and it uses rollup too.

Once you have generated a pair of index.d.{cts,mts} files you can either:

  1. Remove the "types" field from your package.json to let typescript automatically resolve each index.{cjs,mjs} file to the corresponding index.d.{cts,mts} file.
  2. Or, add something like this to your package.json:
"exports": {
  "import": {
    "types": "./dist/index.d.mts",
    "default": "./dist/index.mjs"
  },
  "require": {
    "types": "./dist/index.d.cts",
    "default": "./dist/index.cjs"
  }
}

Source: ianstormtaylor/superstruct