Skip to content

Incorrect support of exports in package.json when generating CommonJS files #54263

@qraynaud

Description

@qraynaud

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    ExternalRelates to another program, environment, or user action which we cannot control.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions