typescript 如何从现有的 JavaScript 库生成 .d.ts “typings”定义文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12687779/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do you produce a .d.ts "typings" definition file from an existing JavaScript library?
提问by Hotrodmonkey
I'm using a lot of libraries both my own and 3rd party. I see the "typings" directory contains some for Jquery and WinRT... but how are they created?
我使用了很多我自己的和第三方的库。我看到“typings”目录包含一些用于 Jquery 和 WinRT 的……但是它们是如何创建的?
回答by Ryan Cavanaugh
There are a few options available for you depending on the library in question, how it's written, and what level of accuracy you're looking for. Let's review the options, in roughly descending order of desirability.
有几个选项可供您使用,具体取决于相关库、它的编写方式以及您正在寻找的准确度级别。让我们按照需求的大体降序来回顾一下这些选项。
Maybe It Exists Already
也许它已经存在
Always check DefinitelyTyped (https://github.com/DefinitelyTyped/DefinitelyTyped) first. This is a community repo full of literally thousands of .d.ts files and it's very likely the thing you're using is already there. You should also check TypeSearch (https://microsoft.github.io/TypeSearch/) which is a search engine for NPM-published .d.ts files; this will have slightly more definitions than DefinitelyTyped. A few modules are also shipping their own definitions as part of their NPM distribution, so also see if that's the case before trying to write your own.
始终首先检查绝对类型(https://github.com/DefinitelyTyped/DefinitelyTyped)。这是一个充满了数以千计的 .d.ts 文件的社区存储库,很可能您正在使用的东西已经存在。您还应该检查 TypeSearch ( https://microsoft.github.io/TypeSearch/),它是 NPM 发布的 .d.ts 文件的搜索引擎;这将比绝对类型有更多的定义。一些模块也将它们自己的定义作为其 NPM 发行版的一部分发布,因此在尝试编写自己的模块之前还要看看是否是这种情况。
Maybe You Don't Need One
也许你不需要一个
TypeScript now supports the --allowJs
flag and will make more JS-based inferences in .js files. You can try including the .js file in your compilation along with the --allowJs
setting to see if this gives you good enough type information. TypeScript will recognize things like ES5-style classes and JSDoc comments in these files, but may get tripped up if the library initializes itself in a weird way.
TypeScript 现在支持该--allowJs
标志,并将在 .js 文件中进行更多基于 JS 的推断。您可以尝试在编译中包含 .js 文件以及--allowJs
设置,以查看这是否为您提供了足够好的类型信息。TypeScript 会识别这些文件中的 ES5 样式类和 JSDoc 注释之类的东西,但如果库以一种奇怪的方式初始化自己,则可能会被绊倒。
Get Started With --allowJs
开始使用 --allowJs
If --allowJs
gave you decent results and you want to write a better definition file yourself, you can combine --allowJs
with --declaration
to see TypeScript's "best guess" at the types of the library. This will give you a decent starting point, and may be as good as a hand-authored file if the JSDoc comments are well-written and the compiler was able to find them.
如果--allowJs
给你不错的结果,并要写出更好的定义文件自己,你可以结合--allowJs
使用--declaration
,看打字稿的“最佳猜测”的类型库。这将为您提供一个不错的起点,如果 JSDoc 注释写得很好并且编译器能够找到它们,那么它可能与手工编写的文件一样好。
Get Started with dts-gen
开始使用 dts-gen
If --allowJs
didn't work, you might want to use dts-gen (https://github.com/Microsoft/dts-gen) to get a starting point. This tool uses the runtime shape of the object to accurately enumerate all available properties. On the plus side this tends to be very accurate, but the tool does not yet support scraping the JSDoc comments to populate additional types. You run this like so:
如果--allowJs
不起作用,您可能想使用 dts-gen ( https://github.com/Microsoft/dts-gen) 来获得一个起点。此工具使用对象的运行时形状来准确枚举所有可用属性。从好的方面来说,这往往非常准确,但该工具尚不支持抓取 JSDoc 注释以填充其他类型。你像这样运行:
npm install -g dts-gen
dts-gen -m <your-module>
This will generate your-module.d.ts
in the current folder.
这将your-module.d.ts
在当前文件夹中生成。
Hit the Snooze Button
点击贪睡按钮
If you just want to do it all later and go without types for a while, in TypeScript 2.0 you can now write
如果你只是想稍后再做这一切并且暂时不用类型,那么在 TypeScript 2.0 中,你现在可以编写
declare module "foo";
which will let you import
the "foo"
module with type any
. If you have a global you want to deal with later, just write
这将使您拥有 typeimport
的"foo"
模块any
。如果你有一个你想稍后处理的全局,只需写
declare const foo: any;
which will give you a foo
variable.
这会给你一个foo
变量。
回答by JayKan
You can either use tsc --declaration fileName.ts
like Ryan describes, or you can specify declaration: true
under compilerOptions
in your tsconfig.json
assuming you've already had a tsconfig.json
under your project.
您可以使用tsc --declaration fileName.ts
像瑞安介绍,也可以指定declaration: true
下compilerOptions
你tsconfig.json
假设你已经有一个tsconfig.json
项目下。
回答by Gorgi Kosev
The best way to deal with this (if a declaration file is not available on DefinitelyTyped) is to write declarations only for the things you use rather than the entire library. This reduces the work a lot - and additionally the compiler is there to help out by complaining about missing methods.
处理这个问题的最好方法(如果声明文件在绝对类型上不可用)是只为你使用的东西而不是整个库编写声明。这大大减少了工作量 - 此外,编译器可以通过抱怨缺少方法来提供帮助。
回答by CCoder
As Ryan says, the tsc compiler has a switch --declaration
which generates a .d.ts
file from a .ts
file. Also note that (barring bugs) TypeScript is supposed to be able to compile Javascript, so you can pass existing javascript code to the tsc compiler.
正如 Ryan 所说,tsc 编译器有一个开关--declaration
,可以.d.ts
从.ts
文件生成文件。另请注意(排除错误)TypeScript 应该能够编译 Javascript,因此您可以将现有的 javascript 代码传递给 tsc 编译器。
回答by zowers
as described in http://channel9.msdn.com/posts/Anders-Hejlsberg-Steve-Lucco-and-Luke-Hoban-Inside-TypeScriptat 00:33:52 they had built a tool to convert WebIDL and WinRT metadata into TypeScript d.ts
如http://channel9.msdn.com/posts/Anders-Hejlsberg-Steve-Lucco-and-Luke-Hoban-Inside-TypeScript在 00:33:52 中所述,他们构建了一个工具来将 WebIDL 和 WinRT 元数据转换为打字稿 d.ts
回答by Shaun Luttin
Here is some PowerShell that creates a single TypeScript definition file a library that includes multiple *.js
files with modern JavaScript.
下面是一些 PowerShell,它创建一个单一的 TypeScript 定义文件,一个包含多个*.js
现代 JavaScript文件的库。
First, change all the extensions to .ts
.
首先,将所有扩展名更改为.ts
.
Get-ChildItem | foreach { Rename-Item $_ $_.Name.Replace(".js", ".ts") }
Second, use the TypeScript compiler to generate definition files. There will be a bunch of compiler errors, but we can ignore those.
其次,使用 TypeScript 编译器生成定义文件。会有一堆编译器错误,但我们可以忽略它们。
Get-ChildItem | foreach { tsc $_.Name }
Finally, combine all the *.d.ts
files into one index.d.ts
, removing the import
statements and removing the default
from each export statement.
最后,将所有*.d.ts
文件合并为一个index.d.ts
,删除import
语句并default
从每个导出语句中删除。
Remove-Item index.d.ts;
Get-ChildItem -Path *.d.ts -Exclude "Index.d.ts" | `
foreach { Get-Content $_ } | `
where { !$_.ToString().StartsWith("import") } | `
foreach { $_.Replace("export default", "export") } | `
foreach { Add-Content index.d.ts $_ }
This ends with a single, usable index.d.ts
file that includes many of the definitions.
这以index.d.ts
包含许多定义的单个可用文件结束。
回答by magikMaker
When creating your own library, you can can create *.d.ts
files by using the tsc
(TypeScript Compiler) command like so:
(assuming you're building your library to the dist/lib
folder)
创建自己的库时,您可以*.d.ts
使用tsc
(TypeScript Compiler) 命令创建文件, 如下所示:(假设您正在将库构建到dist/lib
文件夹中)
tsc -d --declarationDir dist/lib --declarationMap --emitDeclarationOnly
-d
(--declaration
): generates the*.d.ts
files--declarationDir dist/lib
: Output directory for generated declaration files.--declarationMap
: Generates a sourcemap for each corresponding ‘.d.ts' file.--emitDeclarationOnly
: Only emit ‘.d.ts' declaration files. (no compiled JS)
-d
(--declaration
): 生成*.d.ts
文件--declarationDir dist/lib
: 生成的声明文件的输出目录。--declarationMap
:为每个相应的“.d.ts”文件生成一个源映射。--emitDeclarationOnly
: 只发出 '.d.ts' 声明文件。(没有编译的JS)
(see the docsfor all command line compiler options)
(有关所有命令行编译器选项,请参阅文档)
Or for instance in your package.json
:
或者例如在您的package.json
:
"scripts": {
"build:types": "tsc -d --declarationDir dist/lib --declarationMap --emitDeclarationOnly",
}
and then run: yarn build:types
(or npm run build:types
)
然后运行:(yarn build:types
或npm run build:types
)
回答by camelCase
I would look for an existing mapping of your 3rd party JS libraries that support Script# or SharpKit. Users of these C# to .js cross compilers will have faced the problem you now face and might have published an open source program to scan your 3rd party lib and convert into skeleton C# classes. If so hack the scanner program to generate TypeScript in place of C#.
我会寻找支持 Script# 或 SharpKit 的第 3 方 JS 库的现有映射。这些 C# 到 .js 交叉编译器的用户将面临您现在面临的问题,并且可能已经发布了一个开源程序来扫描您的 3rd 方库并将其转换为骨架 C# 类。如果是这样,请破解扫描仪程序以生成 TypeScript 来代替 C#。
Failing that, translating a C# public interface for your 3rd party lib into TypeScript definitions might be simpler than doing the same by reading the source JavaScript.
如果做不到这一点,将您的 3rd 方库的 C# 公共接口转换为 TypeScript 定义可能比通过阅读源 JavaScript 执行相同操作更简单。
My special interest is Sencha's ExtJS RIA framework and I know there have been projects published to generate a C# interpretation for Script# or SharpKit
我特别感兴趣的是 Sencha 的 ExtJS RIA 框架,我知道已经发布了一些项目来为 Script# 或 SharpKit 生成 C# 解释