Skip to main content

添加 Flow

Flow 是一种静态类型检查器,可帮助你编写错误更少的代码。如果你不熟悉此概念,请查看此 在 JavaScript 中使用静态类型的介绍

¥Flow is a static type checker that helps you write code with fewer bugs. Check out this introduction to using static types in JavaScript if you are new to this concept.

Flow 的最新版本可以开箱即用地使用 Create React App 项目。

¥Recent versions of Flow work with Create React App projects out of the box.

要将 Flow 添加到 Create React App 项目,请执行以下步骤:

¥To add Flow to a Create React App project, follow these steps:

  1. 运行 npm install --save flow-bin(或 yarn add flow-bin)。

    ¥Run npm install --save flow-bin (or yarn add flow-bin).

  2. "flow": "flow" 添加到 package.jsonscripts 部分。

    ¥Add "flow": "flow" to the scripts section of your package.json.

  3. 运行 npm run flow init(或 yarn flow init)以在根目录中创建 .flowconfig 文件

    ¥Run npm run flow init (or yarn flow init) to create a .flowconfig file in the root directory.

  4. // @flow 添加到你要进行类型检查的任何文件(例如,添加到 src/App.js)。

    ¥Add // @flow to any files you want to type check (for example, to src/App.js).

现在你可以运行 npm run flow(或 yarn flow)来检查文件的类型错误。你可以选择为你的 IDE 启用扩展,例如 Visual Studio Code 的 Flow 语言支持,或利用语言服务器协议标准(例如 vim LSP)在你键入时获得提示。

¥Now you can run npm run flow (or yarn flow) to check the files for type errors.\ You can optionally enable an extension for your IDE, such as Flow Language Support for Visual Studio Code, or leverage the Language Server Protocol standard (e.g. vim LSP) to get hints while you type.

如果你想将 绝对导入 与 Flow 一起使用,请确保将以下行添加到你的 .flowconfig 以让 Flow 知道它:

¥If you'd like to use absolute imports with Flow, make sure to add the following line to your .flowconfig to make Flow aware of it:

  [options]
+ module.name_mapper='^\([^\.].*\)$' -> '<PROJECT_ROOT>/src/\1'

要了解有关 Flow 的更多信息,请查看 它的文档

¥To learn more about Flow, check out its documentation.