andrewbranch / example-subpath-exports-ts-compat

TypeScript-friendly strategies for package.json subpath exports compatibility

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Clarify separate types for CJS and ESM in package.json redirect strategy

thomasballinger opened this issue · comments

The package-json-redirect README describes separate types for CJS and ESM files also being possible with the package.json redirect strategy.

Note that the separate handling of ESM and CJS, as well as the decision to present a unified set of types for the two, is orthogonal to the subpath exports demonstration. (Including separate types for CJS and ESM files, as extensionless does, is often a better choice, and is compatible with this strategy.)

How is this compatible, with just one types field of the package.json would that be accomplished with two sets of types in a redirected-to directory with .d.mts and .d.ts extensions? And the types field should have no extension?

When I type it out it seems obvious, I guess my confusion was around which file extensions tricks were unique to the "extensionless" approach.

It hadn't occurred to me until a tweet from @andrewbranch that you can nest types conditions inside of import/require/default conditions. So that's one way to do this, I tried this and it seems to work.

"exports": {
    ".": {
      "import": {
        "types": "./types/index.d.ts",
        "import": "./esm/index.js"
      },
      "default": {
        "types": "./types/index.d.ts",
        "default": "./cjs/index.js"
      }
    },
    "./one": {
      "import": {
        "types": "./types/one.d.ts",
        "import": "./esm/one.js"
      },
      "default": {
        "types": "./types/one.d.ts",
        "default": "./cjs/one.js"
      }
    },
    ...

Yeah, in most cases I think `types` should not be used. This was not well-communicated (and tbh not even well-understood on the team) at the beginning. If used in a dual CJS/ESM package, it needs to be nested in separate `import` and `require` conditions, not siblings to them.

@andrewbranch@fosstodon.org (@atcb) January 30, 2023