@babel/plugin-transform-block-scoping
这个插件包含在 @babel/preset-env 中
示例
🌐 Examples
在
{
let a = 3;
}
let a = 3;
出
{
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
- Yarn
- pnpm
- Bun
npm install --save-dev @babel/plugin-transform-block-scoping
yarn add --dev @babel/plugin-transform-block-scoping
pnpm add --save-dev @babel/plugin-transform-block-scoping
bun add --dev @babel/plugin-transform-block-scoping
用法
🌐 Usage
使用配置文件(推荐)
🌐 With a configuration file (Recommended)
没有选项:
🌐 Without options:
{
"plugins": ["@babel/plugin-transform-block-scoping"]
}
有选项:
🌐 With options:
{
"plugins": [
[
"@babel/plugin-transform-block-scoping",
{
"throwIfClosureRequired": true
}
]
]
}
通过 CLI
🌐 Via CLI
babel --plugins @babel/plugin-transform-block-scoping script.js
通过 Node API
🌐 Via Node API
require("@babel/core").transformSync("code", {
plugins: ["@babel/plugin-transform-block-scoping"],
});
选项
🌐 Options
throwIfClosureRequired
boolean,默认值为 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:
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。
默认情况下,这个插件会忽略块级作用域变量的 暂时性死区 (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:
i;
let i;
如果你需要这些错误,你可以通过为这个插件设置 "tdz": true 来让 Babel 尝试找到它们。不过,目前的实现可能无法处理所有边缘情况,最好一开始就避免写这样的代码。
🌐 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.
你可以在这里了解更多关于配置插件选项的内容