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?
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:
- Add
"declaration": true
to tsconfig - Add
"outDir": "dist"
to tsconfig - Add dist to .gitignore
- Add .npmignore like .gitignore but without dist
- Add
"main": "dist/index.js"
in package.json (note the "js" suffix and dist directory) - 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.
© 2022 - 2024 — McMap. All rights reserved.
"declaration": true
compiler option – Strader