npmtypescript-typings

Publishing a library with declaration files


I've added type support to a library via declaration files (.d.ts) generated from jsdocs. However, when the library is consumed (ex import foo from 'the-library/foo'), TypeScript complains Cannot find module … or its corresponding type declarations .ts(2307). Strangely (possibly a red-herring), cmd + click in VS Code no-longer jumps to the file.

The library is not bundled, and thus, nor are the types. The TS documentation on publishing a library covers only the bundled scenario (which makes no sense as libraries are usually not bundled).

The individual declaration files are co-located with the implementation files like so:

./lib/
  ├ foo.js
  └ foo.d.ts

and my package.json exports the typings:

{
  "name": "the-library",
  "type": "module",
  "files": ["./lib/**/*"],
  "exports": {
    "foo": {
      "default": "./lib/foo.js",
      "types": "./lib/foo.d.ts"
    }
  }
}

I tried a root-level "types" field in package.json with a barrel types file, but that produced the same TS error.

The generated declaration files appear to be fine, and within the library, VS Code IntelliSense consumes them just fine.

All the questions I see on SO seemed to be answered by "restart the TS server", which I did to no avail.


Solution

  • TypeScript complains Cannot find module … or its corresponding type declarations .ts(2307). Strangely (possibly a red-herring), cmd + click in VS Code no-longer jumps to the file.

    This was caused by a too quick-n-dirty minimum-repo setup: VS Code (TypeScript) was just having a tantrum when there is no tsconfig.json (in the consuming project). It needed that with moduleResolution (it's working with "moduleResolution": "NodeNext" and no other compiler options specified). Without the tsconfig, it throws a bunch of misleading errors (imagine TypeScript throwing a misleading error? never…).

    And in order for TypeScript to pick up the types, they do indeed need to be included in the library's package.json's exports (like how they are in the question). Omitting them results in the same Cannot find module … or its corresponding type declarations in the consuming project.