Skip to main content

安装

设置编译器

¥Setup Compiler

首先,你需要设置一个编译器来剥离 Flow 类型。你可以在 Babelflow-remove-types 之间进行选择。

¥First you'll need to setup a compiler to strip away Flow types. You can choose between Babel and flow-remove-types.

Babel 是一个支持 Flow 的 JavaScript 代码编译器。Babel 将获取你的 Flow 代码并删除任何类型注释。如果你已经在项目中使用 Babel,请参阅 使用 Babel

¥Babel is a compiler for JavaScript code that has support for Flow. Babel will take your Flow code and strip out any type annotations. If you already use Babel in your project, see using Babel.

首先安装 @babel/core@babel/cli@babel/preset-flowbabel-plugin-syntax-hermes-parser 以及 Yarnnpm

¥First install @babel/core, @babel/cli, @babel/preset-flow, and babel-plugin-syntax-hermes-parser with either Yarn or npm.

npm install --save-dev @babel/core @babel/cli @babel/preset-flow babel-plugin-syntax-hermes-parser

接下来,你需要使用 @babel/preset-flow 预设和 babel-plugin-syntax-hermes-parser 插件在项目的根目录下创建 .babelrc 文件。

¥Next you need to create a .babelrc file at the root of your project with the @babel/preset-flow preset and babel-plugin-syntax-hermes-parser plugin.

{
"presets": ["@babel/preset-flow"],
"plugins": ["babel-plugin-syntax-hermes-parser"],
}

如果你将所有源文件放在 src 目录中,则可以通过运行以下命令将它们编译到另一个目录:

¥If you then put all your source files in a src directory you can compile them to another directory by running:

./node_modules/.bin/babel src/ -d lib/

你可以轻松地将其添加到你的 package.json 脚本中,以及 Babel 上的 "devDependencies" 脚本中。

¥You can add this to your package.json scripts easily, alongside your "devDependencies" on Babel.

{
"name": "my-project",
"main": "lib/index.js",
"scripts": {
"build": "babel src/ -d lib/",
"prepublish": "yarn run build"
}
}

注意:你可能还需要添加一个运行此转换的 prepublish 脚本,以便它在将代码发布到 npm 注册表之前运行。

¥Note: You'll probably want to add a prepublish script that runs this transform as well, so that it runs before you publish your code to the npm registry.

设置 Flow

¥Setup Flow

Flow 在使用显式版本控制按项目安装时效果最佳,而不是全局安装。

¥Flow works best when installed per-project with explicit versioning rather than globally.

幸运的是,如果你已经熟悉 npmyarn,那么这个过程应该非常熟悉!

¥Luckily, if you're already familiar with npm or yarn, this process should be pretty familiar!

flow-bin npm 包上添加 devDependency

¥Add a devDependency on the flow-bin npm package

npm install --save-dev flow-bin

"flow" 脚本添加到 package.json

¥Add a "flow" script to your package.json

{
"name": "my-flow-project",
"version": "1.0.0",
"devDependencies": {
"flow-bin": "^0.253.0"
},
"scripts": {
"flow": "flow"
}
}

运行 Flow

¥Run Flow

第一次,运行:

¥The first time, run:

npm run flow init
> my-flow-project@1.0.0 flow /Users/Projects/my-flow-project
> flow "init"

第一次使用 init 运行 flow 后,运行:

¥After running flow with init the first time, run:

npm run flow
> my-flow-project@1.0.0 flow /Users/Projects/my-flow-project
> flow

No errors!

设置 ESLint

¥Setup ESLint

如果你使用 ESLint,你可以阅读 我们在 ESLint 上的页面 来设置它支持 Flow。

¥If you use ESLint, you can read our page on ESLint to set it up to support Flow.