balazsbotond / urlcat

A URL builder library for JavaScript.
https://urlcat.org
MIT License
1.82k stars 57 forks source link

Add "types" import condition to fix esm type definition file not found #257

Open isudzumi opened 1 year ago

isudzumi commented 1 year ago

Summary

close https://github.com/balazsbotond/urlcat/issues/248

As of Typescript 4.7, when esmodule applications with moduleResolution: nodenext use this library, Typescript cannot find a declaration file for .mjs file (https://devblogs.microsoft.com/typescript/announcing-typescript-4-7/#package-json-exports-imports-and-self-referencing). To fix the problem, add "types" field to import condition.

Details

About the problem

Here is example:

package.json

{
  "type": "module",
  "dependencies": {
    "urlcat": "^3.1.0"
  },
  "devDependencies": {
    "typescript": "^5.0.4"
  }
}

tsconfig.json

{
  "compilerOptions": {
    "module": "nodenext",
    "moduleResolution": "nodenext",
    "strict": true
  }
}

This emits the following error

index.ts:1:20 - error TS7016: Could not find a declaration file for module 'urlcat'. 'node_modules/urlcat/dist/index.mjs' implicitly has an 'any' type.
  There are types at 'node_modules/urlcat/dist/index.d.ts', but this result could not be resolved when respecting package.json "exports". The 'urlcat' library may need to update its package.json or typings.

1 import urlcat from "urlcat";
                     ~~~~~~~~

Found 1 error in index.ts:1

This PR fixes the issue.

About postbuild

To find type definition file for .mjs, it requires .d.mts. Ideally, tsup should add support for generating .d.mts or .d.cts file, but currently the feature is not implemented (https://github.com/egoist/tsup/issues/760). So this PR copies .d.ts to .d.mts in a postbuild script as a workaround.

omarkhatibco commented 11 months ago

could you update this PR, tsup supports exporting .d.cts now. https://github.com/egoist/tsup/pull/934