milesj/packemon

TypeScript library with `"type": "module"` generating `cjs` declarations with `.d.ts` suffix

NexZhu opened this issue · 6 comments

NexZhu commented

I have a TypeScript library with "type": "module" , I want to build both ESM and CommonJS output.

package.json:

  "packemon": {
    "format": [
      "esm",
      "cjs"
    ],
    "platform": [
      "node",
      "browser"
    ],
    "api": "public"
  },

Generated esm output looks fine but the cjs output also has declarations with .d.ts suffixes instead of .d.cts.
image

This will cause problems in CommonJS project importing the library.
See:
microsoft/TypeScript#50466 (comment)
microsoft/TypeScript#50466 (comment)

milesj commented

@NexZhu The .d.cts extension only works if your source files are .cts and not .ts. This is a TS thing, not a Packemon thing.

NexZhu commented

@milesj I understand TS doesn't handle that, but I think this tool can do it by renaming file extensions. Because but hybrid package with both ESM and CommonJS build output won't be useful without .cts extensions because with "type": "module" in package.json, even if you have:

  "exports": {
    "./some-path": {
      "import": {
        "default": "./dist/esm/some-path/index.js",
        "types": "./dist/esm/some-path/index.d.ts"
      },
      "require": {
        "default": "./dist/cjs/some-path/index.cjs", # or .js doesn't matter
        "types": "./dist/cjs/some-path/index.d.ts" # This will cause issue if used in CommonJS + TypeScript project
      }
    }
  },

If you try to import this library from a CommonJS + TypeScript project like:

import { xxx } from 'library-name/some-path'

You will get this error, making it not usable from CommonJS + TypeScript project:
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' (ts1479)

The links I posted above explain the issue in detail.

So, what I'm thinking is, for this tool to be useful for building hybrid package with both ESM and CommonJS build output, it'd better take care of outputting the .cts extensions for CommonJS by renaming files maybe.

milesj commented

@NexZhu Not sure I feel about this since it feels like a "hack" but I'll support it anyways through a setting.

milesj commented

@NexZhu Starting on this here: #213

Can you take a look and see if that solves your problem?

NexZhu commented

Yes. Thanks!