Skip to content

"Compile TypeScript Libraries to Multiple Formats" article produces invalid packages #33258

@tylerbutler

Description

@tylerbutler

Documentation issue

  • Reporting a typo
  • Reporting a documentation bug
  • Documentation improvement
  • Documentation feedback

Is there a specific documentation page you are reporting?

https://nx.dev/docs/technologies/typescript/guides/compile-multiple-formats

Additional context or description

If one follows the pattern described here, it will produce packages that are not usable with modern TypeScript module resolution. To be correct, the exports must include a types entrypoint for both ESM and CJS. You may be tempted to use the same types file path for both ESM and CJS, but this doesn't work.

There are even more details in the TypeScript handbook, but I find the are-thetype-wrong docs to be the most practically helpful, and this section from the TypeScript 4.7 release notes covers it pretty well (emphasis added):

It’s important to note that the CommonJS entrypoint and the ES module entrypoint each needs its own declaration file, even if the contents are the same between them. Every declaration file is interpreted either as a CommonJS module or as an ES module, based on its file extension and the "type" field of the package.json, and this detected module kind must match the module kind that Node will detect for the corresponding JavaScript file for type checking to be correct. Attempting to use a single .d.ts file to type both an ES module entrypoint and a CommonJS entrypoint will cause TypeScript to think only one of those entrypoints exists, causing compiler errors for users of the package.

For more context, you can check these PRs where I have fixed various projects' types because they have similar problems. Unfortunately unless one is using a tool like are-the-types-wrong or tests their package in all typescript compilation configs, the bug is easy to miss until someone can't compile their typescript project using the package.

If you could use your documentation to raise awareness about this common mistake, it would really help improve the ecosystem. It's been years and I am still run into packages that aren't configured correctly.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions