How to generate type definition file from TypeScript files?
Asked Answered
T

1

5

I crafted some classes and modules in TypeScript. Other TypeScript apps can use the TS files directly without needing type definitions. However, to publish to npm, I guess I need to publish both JS files and the type definition files. I think it could be wasteful to hand-craft d.ts files, so How to generate type definition files from TypeScript files?

Tsarevna answered 14/9, 2018 at 5:8 Comment(1)
Just set "declaration": true compiler optionStrader
C
11

Short answer

Add "declaration": true to your tsconfig to have *.d.ts files generated along with *.js files

Long answer

To publish *.js and *.d.ts files to npm but not to github (generally you want to keep only source in your source control) you need to do few things:

  1. Add "declaration": true to tsconfig
  2. Add "outDir": "dist" to tsconfig
  3. Add dist to .gitignore
  4. Add .npmignore like .gitignore but without dist
  5. Add "main": "dist/index.js" in package.json (note the "js" suffix and dist directory)
  6. Add "types": "dist/index.d.ts" in package.json (note the "ts" suffix this time and dist directory)

(Your file names and directories may vary of course, the above is assuming that your distribution directory is dist and your main entry point is index.ts)

This is without configuring build scripts, just a bare minimum to have published what you need so that other Node modules and programs could require your module using both JavaScript and TypeScript, without keeping generated files under source control.

For more details see:

This is an answer that I wrote while preparing my talk about Deno (slides, video) trying describe the entire process of publishing Node modules written in TypeScript to npm, which is exactly what you are doing here so maybe you'll find more useful info not only about generating .d.ts files but also other related things.

Cartie answered 14/5, 2019 at 7:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.