Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
sydonia86 opened this issue Nov 29, 2024 · 1 comment

Comments

@sydonia86
Copy link

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

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

tsconfig.json

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

index.ts

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"
  }
}
@yeoffrey
Copy link
Contributor

yeoffrey commented Dec 1, 2024

@arturmuller This seems like something critical.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants