库定义
什么是 "库定义"?
¥What's a "Library Definition"?
大多数真正的 JavaScript 程序都依赖于第三方代码,而不仅仅是直接受项目控制的代码。这意味着使用 Flow 的项目可能需要引用没有类型信息或没有准确和/或精确类型信息的外部代码。为了解决这个问题,Flow 支持 "库定义"(又名 "库定义文件")的概念。
¥Most real JavaScript programs depend on third-party code and not just code immediately under the control of the project. That means a project using Flow may need to reference outside code that either doesn't have type information or doesn't have accurate and/or precise type information. In order to handle this, Flow supports the concept of a "library definition" (a.k.a. "libdef").
libdef 是一个特殊文件,它向 Flow 通知你的应用使用的某些特定第三方模块或模块包的类型签名。如果你熟悉具有头文件的语言(例如 C++
),你可以将 libdef 视为类似的概念。
¥A libdef is a special file that informs Flow about the type signature of some
specific third-party module or package of modules that your application uses.
If you're familiar with languages that have header files (like C++
), you can
think of libdefs as a similar concept.
这些特殊文件使用与普通 JS 代码相同的 .js
扩展名,但它们放置在项目根目录中名为 flow-typed
的目录中。放置在此目录中会告诉 Flow 将它们解释为 libdef,而不是普通的 JS 文件。
¥These special files use the same .js
extension as normal JS code, but they are
placed in a directory called flow-typed
in the root directory of your project.
Placement in this directory tells Flow to interpret them as libdefs rather than
normal JS files.
注意:使用 libdefs 的
/flow-typed
目录是一种约定,它使 Flow 能够开箱即用,并鼓励使用 Flow 的项目之间的一致性,但也可以显式配置 Flow 以使用.flowconfig
的[libs]
部分 在其他地方查找 libdefs。¥NOTE: Using the
/flow-typed
directory for libdefs is a convention that enables Flow to JustWork™ out of the box and encourages consistency across projects that use Flow, but it is also possible to explicitly configure Flow to look elsewhere for libdefs using the[libs]
section of your.flowconfig
.
你还可以了解 声明文件。
¥You can also learn about declaration files.
一般最佳实践
¥General Best Practices
尝试为你的项目使用的每个第三方库提供一个 libdef。
¥Try to provide a libdef for each third-party library your project uses.
如果你的项目使用没有类型信息的第三方库,Flow 会将其视为任何其他无类型依赖,并将其所有导出标记为 any
。
¥If a third-party library that has no type information is used by your project,
Flow will treat it like any other untyped dependency and mark all of its exports
as any
.
由于这种行为,最佳实践是为你使用的尽可能多的第三方库查找或编写 libdef。我们建议查看 flow-typed
工具和存储库 ,它可以帮助你快速查找并安装第三方依赖的预先存在的 libdef。
¥Because of this behavior, it is a best practice to find or write libdefs for as
many of the third-party libraries that you use as you can. We recommend checking
out the flow-typed
tool and repository
, which helps you quickly find and install pre-existing libdefs for your
third-party dependencies.