TypeScript: Incorrect support of `exports` in `package.json` when generating CommonJS files

Bug Report

๐Ÿ”Ž Search Terms

  • ts1479
  • exports
  • package.json

๐Ÿ•— Version & Regression Information

  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about 5m

๐Ÿ’ป Code

Very simple codebase:

import { divide, round } from "mathjs"

Using the following tsconfig.json :

{
  "compilerOptions": {
    "moduleResolution": "nodenext",
    "module": "commonjs",
  }
}

๐Ÿ™ Actual behavior

Typescript generates the following error message:

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(โ€œmathjsโ€)โ€™ call instead. To convert this file to an ECMAScript module, change its file extension to โ€˜.mtsโ€™, or add the field "type": "module" to โ€˜/path/to/package.jsonโ€™.

๐Ÿ™‚ Expected behavior

This should work. The important parts of the package.json file are:

{
  "type": "module",
  "main": "./lib/cjs",
  "types": "./types/index.d.ts",
  "exports": {
    ".": {
      "types": "./types/index.d.ts",
      "import": "./lib/esm/index.js",
      "require": "./lib/cjs/index.js"
    },
  } 
}

Here is the reference package.json.

Even though the root directory of this file is marked as "type": "module", it has a require exports. And this require exports point to a file in a directory containing a package.json looking like:

{
  "type": "commonjs"
}

Thus, it is a perfectly valid module to be required.

Iโ€™m pretty sure this should work. node requires this module perfectly well without giving an error.

Note: remove "type": "module", from the package.json using a patch fix the issue, but it is a real bother to maintain a patch for each module using this structure (there are a lot more out there).

About this issue

  • Original URL
  • State: closed
  • Created a year ago
  • Reactions: 1
  • Comments: 28 (5 by maintainers)

Most upvoted comments

Maybe the simpler choice would be to remove ts1479 altogether from the codebase. Itโ€™s not very useful to check this in TS since node do at runtime. Itโ€™s always nice to have more checks to prevent mistakes. But maybe this time itโ€™s a little too involved a check to make?