Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate type definition file from TypeScript files?

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?

like image 463
ZZZ Avatar asked Jan 02 '23 21:01

ZZZ


1 Answers

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:

  • https://stackoverflow.com/a/55609763/613198

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.

like image 119
rsp Avatar answered Jan 04 '23 09:01

rsp