Skip to main content

@babel/plugin-transform-block-scoping

信息

此插件包含在 @babel/preset-env

¥This plugin is included in @babel/preset-env

示例

¥Examples

输入

¥In

JavaScript
{
let a = 3;
}

let a = 3;

输出

¥Out

JavaScript
{
var _a = 3;
}

var a = 3;

不断检查

¥Constant checks

此插件还验证所有 const 变量。常量的重新分配是一个运行时错误,它会插入必要的错误代码。

¥This plugin also validates all const variables. Reassignment of constants is a runtime error and it will insert the necessary error code for those.

安装

¥Installation

npm install --save-dev @babel/plugin-transform-block-scoping

用法

¥Usage

¥With a configuration file (Recommended)

没有选项:

¥Without options:

babel.config.json
{
"plugins": ["@babel/plugin-transform-block-scoping"]
}

有选项:

¥With options:

babel.config.json
{
"plugins": [
[
"@babel/plugin-transform-block-scoping",
{
"throwIfClosureRequired": true
}
]
]
}

通过 CLI

¥Via CLI

Shell
babel --plugins @babel/plugin-transform-block-scoping script.js

通过 Node API

¥Via Node API

JavaScript
require("@babel/core").transformSync("code", {
plugins: ["@babel/plugin-transform-block-scoping"],
});

选项

¥Options

throwIfClosureRequired

boolean,默认为 false

¥boolean, defaults to false.

在以下情况下,如果在转换时不添加额外的函数和闭包,就不可能重写 let/const:

¥In cases such as the following it's impossible to rewrite let/const without adding an additional function and closure while transforming:

JavaScript
for (let i = 0; i < 5; i++) {
setTimeout(() => console.log(i), 1);
}

在对性能极为敏感的代码中,这可能是不可取的。如果设置了 "throwIfClosureRequired": true,则 Babel 在转换这些模式时会抛出异常,而不是自动添加附加函数。

¥In extremely performance-sensitive code, this can be undesirable. If "throwIfClosureRequired": true is set, Babel throws when transforming these patterns instead of automatically adding an additional function.

tdz

boolean,默认为 false

¥boolean, defaults to false.

默认情况下,此插件将忽略块作用域变量的时间死区 (TDZ)。以下代码在使用 Babel 进行转译时不会抛出错误,这不符合规范:

¥By default this plugin will ignore the temporal dead zone (TDZ) for block-scoped variables. The following code will not throw an error when transpiled with Babel, which is not spec compliant:

JavaScript
i;
let i;

如果你需要这些错误,你可以告诉 Babel 通过为这个插件设置 "tdz": true 来尝试找到它们。但是,当前的实现可能无法正确处理所有边缘情况,最好一开始就避免使用这样的代码。

¥If you need these errors you can tell Babel to try and find them by setting "tdz": true for this plugin. However, the current implementation might not get all edge cases right and its best to just avoid code like this in the first place.

提示

你可以阅读有关配置插件选项 此处 的更多信息

¥You can read more about configuring plugin options here