Skip to main content

@babel/preset-flow

如果你使用 Flow,一个用于 JavaScript 代码的静态类型检查器,建议使用这个预设。它包括以下插件:

🌐 This preset is recommended if you use Flow, a static type checker for JavaScript code. It includes the following plugins:

示例​

🌐 Example

在

JavaScript
function foo(one: any, two: number, three?): string {}

出

JavaScript
function foo(one, two, three) {}

安装​

🌐 Installation

npm install --save-dev @babel/preset-flow

用法​

🌐 Usage

🌐 With a configuration file (Recommended)

babel.config.json
{
"presets": ["@babel/preset-flow"]
}

通过 CLI​

🌐 Via CLI

Shell
babel --presets @babel/preset-flow script.js

通过 Node API​

🌐 Via Node API

JavaScript
require("@babel/core").transformSync("code", {
presets: ["@babel/preset-flow"],
});

选项​

🌐 Options

all​

boolean,默认值为 false。

只有在文件顶部存在 @flow 指令,或者在 .flowconfig 中设置了 all 选项 时,Flow 才会解析 Flow 特有的功能。

🌐 Flow will only parse Flow-specific features if a @flow pragma is present atop the file, or the all option is set inside the .flowconfig.

如果你在 Flow 配置中使用 all 选项,记得把这个选项设置为 true,这样行为才能匹配。

🌐 If you are using the all option in your Flow config, be sure to set this option to true to get matching behavior.

例如,如果没有上述任何一种设置,则以下调用表达式带有类型参数:

🌐 For example, without either of the above set, the following call expression with a type argument:

f<T>(e)

将被解析为嵌套的二进制表达式:

🌐 Would get parsed as a nested binary expression:

JavaScript
f < T > e;

allowDeclareFields​

boolean,默认值为 false

已添加于:v7.9.0

🌐 Added in: v7.9.0

note

这将在 Babel 8 中默认启用

启用时,只有当类型专用的类字段带有 declare 修饰符前缀时,它们才会被移除:

🌐 When enabled, type-only class fields are only removed if they are prefixed with the declare modifier:

JavaScript
class A {
declare foo: string; // Removed
bar: string; // Initialized to undefined
}

ignoreExtensions​

boolean,默认值为 false

历史
版本变更
v8.0.0默认值更改为 false
v7.24.0新增,默认值为 true

当设置为 true 时,Babel 会对所有扩展名应用 flow 转换。当设置为 false 时,Babel 会避免对 *.tsx 文件进行 flow 转换。

🌐 When it is set to true, Babel will apply the flow transform to all extensions. When it is set to false, Babel will avoid the flow transform for *.tsx files.

experimental_useHermesParser​

boolean,默认值为 false

已添加于:v7.24.0

🌐 Added in: v7.24.0

Hermes 团队正在维护一个替代的 Flow 解析器用于 Babel,它可以更好地跟上最新的 Flow 语法特性。你可以通过将这个选项设置为 true 来启用它。

🌐 The Hermes team is maintaining an alternative Flow parser for Babel, which is better kept up-to-date with the latest Flow syntax features. You can enable it by setting this option to true.

warning

Hermes 解析器目前不会把注释附加到 AST 上。这可能会给依赖特定注释的转换带来问题。

你可以在这里阅读更多关于配置预设选项的信息