简体   繁体   English

如何从TypeScript文件生成类型定义文件?

[英]How to generate type definition file from TypeScript files?

I crafted some classes and modules in TypeScript. 我在TypeScript中制作了一些类和模块。 Other TypeScript apps can use the TS files directly without needing type definitions. 其他TypeScript应用程序可以直接使用TS文件,而无需类型定义。 However, to publish to npm, I guess I need to publish both JS files and the type definition files. 但是,要发布到npm,我想我需要同时发布JS文件和类型定义文件。 I think it could be wasteful to hand-craft d.ts files, so How to generate type definition files from TypeScript files? 我认为手工制作d.ts文件可能很浪费,那么如何从TypeScript文件生成类型定义文件呢?

Short answer 简短答案

Add "declaration": true to your tsconfig to have *.d.ts files generated along with *.js files 在您的tsconfig中添加"declaration": true ,以使* .d.ts文件与* .js文件一起生成

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: 要将* .js和* .d.ts文件发布到npm而不发布到github(通常只希望在源代码管理中保留源代码),您需要做一些事情:

  1. Add "declaration": true to tsconfig 在tsconfig中添加"declaration": true
  2. Add "outDir": "dist" to tsconfig "outDir": "dist"到tsconfig
  3. Add dist to .gitignore 将dist添加到.gitignore
  4. Add .npmignore like .gitignore but without dist 像.gitignore一样添加.npmignore,但是没有dist
  5. Add "main": "dist/index.js" in package.json (note the "js" suffix and dist directory) 在package.json中添加"main": "dist/index.js" (注意“ js”后缀和dist目录)
  6. Add "types": "dist/index.d.ts" in package.json (note the "ts" suffix this time and dist directory) 在package.json中添加"types": "dist/index.d.ts" (注意,这次和dist目录的后缀为“ ts”)

(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 ) (当然,您的文件名和目录可能会有所不同,以上假设您的分发目录是dist而您的主要入口点是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. 这无需配置构建脚本,仅是发布所需内容的最低限度,因此其他Node模块和程序可能需要使用JavaScript和TypeScript的模块,而无需将生成的文件置于源代码控制之下。

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. 这是我在准备有关Deno( 幻灯片视频 )的演讲时写的答案,试图描述将用TypeScript编写的Node模块发布到npm的整个过程,这正是您在这里所做的,所以也许您会发现更多有用的信息不仅涉及生成.d.ts文件,还涉及其他相关内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM