Skip to content

Cannot import a package with "type": "module" from cjs even if the package has an exports map #49299

Closed
@RebeccaStevens

Description

@RebeccaStevens

Bug Report

🔎 Search Terms

  • type: module
  • node16
  • The specifier only resolves to an ES module, which cannot be imported synchronously.

🕗 Version & Regression Information

I was unable to test this on prior versions because it's a brand new feature.

⏯ Playground Link

N/A

💻 Code

Code:

import foo from "my-dep";

tsconfig.json:

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

Dependency's package.json:

{
  "name": "my-dep",
  "type": "module",
  "exports": {
    "types": "index.d.ts",
    "import": "index.mjs",
    "require": "index.cjs"
  }
}

🙁 Actual behavior

Module 'my-dep' cannot be imported using this construct. The specifier only resolves to an ES module, which cannot be imported synchronously. Use dynamic import instead. ts(1471)

🙂 Expected behavior

TypeScript should be able to find the right import of my-dep from its exports map. The type field shouldn't prevent this.

Extra info

If I do any one of the following, everything works as expected.

  • specify "type": "module" in my own package.json
  • remove "type": "module" from my-dep's package.json
  • change my code's file extension to .mts

No changes to tsconfig.json seem to fix the issue.
I would have expected that the following would have worked but it didn't:

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions