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)
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?