Search code examples
javascripttypescriptnpmnpm-workspaces

Best way to share typescript definitions in a npm workspace


I have setup a monorepo using npm's workspaces feature. There are right now two separate apps within the repo that both consume an API that lives in a separate repo. I'd really like to share the API's typescript definitions.

To this end I set up a "common" library in the monorepo for shared code. For code itself this works fine. The JavaScript and its Typescript definitions can be imported into the two other projects in the monorepo. However the API definitions have no corresponding code, they're just d.ts files. The build process ignores them entirely.

All I can think of is to write class definitions in the common library and export those to the other apps, but of course that's not quite as clean as a using d.ts file.

Any other things I could try?


Solution

  • Assuming this project structure:

    ├── apps
    │   ├── app1
    │   └── app2
    ├── shared
    │   ├── src
    │   │   ├── utils
    │   │   └── types
    │   ├── package.json
    │   └── tsconfig.json
    ├── package.json
    └── tsconfig.json
    

    Both apps could reference the generated declarations as usual using the tsconfig.json option references: [{ "path": "../shared" }] which will pick up all generated declarations, e.g. from the .ts files in utils, from the configured outDir of shared

    and additionally include the types manually declared as .d.ts files in shared/src/types with

    "include": [ "../shared/src/types", ... ].

    Or, if the type definitions are not stored in a separate folder, you can include them with a glob pattern like "../shared/src/**/*.d.ts

    Not very convenient, but seems to work.