Skip to content

Issue with ESM and CJS types exports #336

@fir1

Description

@fir1

package.json - has issues regarding ESM and CJS support.

This problem usually happens when a library that includes both a CJS and ESM implementation attempts to use a single .d.ts types file to represent both, where the package.json has "type": "module", most often in a structure like:

{
  "name": "pkg",
  "type": "module",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "import": "./index.js",
      "require": "./index.cjs"
    }
  }
}

If they use import or export at the top level—they must represent exactly one JavaScript file. They especially cannot represent JavaScript files of two different module formats. The example above needs to add a .d.cts file to represent the .cjs file, at which point the package.json can be rewritten as:

{
"name": "pkg",
"type": "module",
"exports": {
".": {
"import": {
"types": "./index.d.ts",
"default": "./index.js"
},
"require": {
"types": "./index.d.cts",
"default": "./index.cjs"
}
}
}
}

The qrcode package is using rollup to build both CJS and EMS modules, there is a known issue with rollup regarding this and possible workaround:
rollup/plugins#1782

Reference to cause and the potential fix:

https://github.com/arethetypeswrong/arethetypeswrong.github.io/blob/main/docs/problems/FalseESM.md

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions