no-lone-blocks
禁止不必要的嵌套块
在 ES6 之前的 JavaScript 中,由花括号分隔的独立代码块不会创建新的作用域,也没有任何用处。例如,这些花括号对 foo
没有任何作用
{
var foo = bar();
}
在 ES6 中,如果存在块级绑定(let
和 const
)、类声明或函数声明(在严格模式下),代码块可能会创建新的作用域。在这种情况下,块不被认为是冗余的。
规则详情
此规则旨在消除脚本顶层或其他块中不必要且可能令人困惑的块。
此规则的 错误 代码示例
在 Playground 中打开
/*eslint no-lone-blocks: "error"*/
if (foo) {
bar();
}
function bar() {
}
class C {
static {
}
}
此规则的 正确 代码示例
在 Playground 中打开
/*eslint no-lone-blocks: "error"*/
while (foo) {
bar();
}
if (foo) {
if (bar) {
baz();
}
}
function bar() {
baz();
}
{
let x = 1;
}
{
const y = 1;
}
{
class Foo {}
}
aLabel: {
}
class C {
static {
lbl: {
if (something) {
break lbl;
}
foo();
}
}
}
此规则的 正确 代码示例,在 ESLint 配置中使用 "parserOptions": { "sourceType": "module" }
或在代码中使用 "use strict"
指令启用 ES6 环境和严格模式
在 Playground 中打开
/*eslint no-lone-blocks: "error"*/
"use strict";
{
function foo() {}
}
版本
此规则在 ESLint v0.4.0 中引入。