我在 npm 上发布了两个 Javascript 库,用户要求为它们提供 TypeScript 类型定义。我自己不使用 TypeScript,也没有计划在 TypeScript 中重写这些库,但如果只是为了更好的 IntelliSense 代码完成,我仍然想添加类型定义文件。我正在寻找与此有关的一些建议。
我开始阅读 DefinitelyTyped project 的文档以及 publishing a declaration file for an npm package 上的文档.两个消息来源都表示“在 npm 上发布到 @types 组织”是非用 TypeScript 编写的项目的首选方法。
为什么比通过 types
与库本身一起发布类型定义更受欢迎字段在 package.json
?我真的不认为让第三方参与其中的意义。通过这种方式更新类型定义和版本化它们似乎更加复杂。
上面引用的文档中的引用(强调我的)
从绝对类型:
If you are the library author and your package is written in TypeScript, bundle the autogenerated declaration files in your package instead of publishing to Definitely Typed.
来自 typescriptlang.org:
Now that you have authored a declaration file following the steps of this guide, it is time to publish it to npm. There are two main ways you can publish your declaration files to npm:
- bundling with your npm package, or
- publishing to the @types organization on npm.
If your package is written in TypeScript then the first approach is favored. Use the --declaration flag to generate declaration files. This way, your declarations and JavaScript will always be in sync.
If your package is not written in TypeScript then the second is the preferred approach.
两者似乎都在说:
if (isAuthor && lang === "typescript")
bundle();
else
publishOnDefinitelyTyped();
最佳答案
类型声明发布指南在几个方面似乎有点过时和稀疏。
我将尝试详细比较这两种情况。
1. 与 npm 包捆绑在一起的类型
1.1.从包装消费者的 Angular
1.1.1.优点
一般来说,由于简化的依赖管理,包捆绑类型更方便。
1.1.2.缺点
涉及消费者需要修改或替换类型声明的情况。
在具有固执的build设置的项目中,该过程可能会出现相当大的问题,
由于已经有限的配置选项。
1.2.从包作者的 Angular 来看
1.2.1.优点
1.2.2.缺点
将类型与包捆绑在一起意味着实际上每次发布一个版本时都会发布两个 API 合约。
例子:
让我们假设一个旨在符合 semver 版本控制的库。
下一版本的选项是:
A. 2.X.X -> 违反了类型声明的 semver 规则
B. 3.0.0 -> 违反实际代码的 semver 规则
这种情况很可能有许多变体。
2. 发布到确定类型的存储库
2.1.从包装消费者的 Angular
2.1.1.优点
2.1.2.缺点
2.2.从包作者的 Angular 来看
2.2.1.优点
第一个工具可以通过较小的努力合并到另一个包存储库中。
我不确定分析是否可以复制到自己的存储库中,但它包含很多有值(value)的数据。
2.2.2.缺点
假设DefinitelyTyped PR创建者是@types包所有者,通常
在 PR 合并之前需要一到两天的时间。另外,还有一个小
类型发布者更新 PR 相关的 @types npm 包之前的延迟。
如果 PR 是作者对给定包的第一个贡献,则涉及额外的审查过程。
typescript 手册说:
If your type definitions depend on another package:
Don’t combine it with yours, keep each in their own file.
Don’t copy the declarations in your package either.
Do depend on the npm type declaration package if it doesn’t package its declaration files.
从冗余实用程序类型的数量来看,这些几乎没有得到尊重。
允许类型声明的作者使用相邻的 DT 存储库类型。
依赖于这个列表之外的包,需要它们在类型发布者白名单上。
可以通过向 types-publisher 提交 PR 来将新包列入白名单。
我的 PR 合并花了两个多星期。我不知道这是否正常,因为我提交了一个 PR。
我没有跨 IDE 的比较或经验,但就 JetBrains IDE 而言,完全索引的 DT 存储库项目的内存占用使 IDE 无法使用。
禁用对更改的重新编译在某种程度上有所帮助。可以通过删除与感兴趣的包无关的 DT 存储库内容来解决令人沮丧的 IDE 体验。
关于javascript - 为什么要为 Javascript 库在绝对类型上发布 TypeScript 声明文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56834190/