no-lone-blocks
禁止不必要的嵌套块
在 ES6 之前的 JavaScript 中,由大括号分隔的独立代码块不会创建新的范围,也没有任何用处。例如,这些大括号对 foo
没有任何作用:
¥In JavaScript, prior to ES6, standalone code blocks delimited by curly braces do not create a new scope and have no use. For example, these curly braces do nothing to foo
:
{
var foo = bar();
}
在 ES6 中,如果存在块级绑定(let
和 const
)、类声明或函数声明(在严格模式下),代码块可能会创建一个新范围。在这些情况下,块不被认为是冗余的。
¥In ES6, code blocks may create a new scope if a block-level binding (let
and const
), a class declaration or a function declaration (in strict mode) are present. A block is not considered redundant in these cases.
规则详情
¥Rule Details
此规则旨在消除脚本顶层或其他块中不必要且可能令人困惑的块。
¥This rule aims to eliminate unnecessary and potentially confusing blocks at the top level of a script or within other blocks.
此规则的错误代码示例:
¥Examples of incorrect code for this rule:
/*eslint no-lone-blocks: "error"*/
{}
if (foo) {
bar();
{
baz();
}
}
function bar() {
{
baz();
}
}
{
function foo() {}
}
{
aLabel: {
}
}
class C {
static {
{
foo();
}
}
}
此规则的正确代码示例:
¥Examples of correct code for this rule:
/*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();
}
}
}
使用 ES6 环境和严格模式(通过 ESLint 配置中的 "parserOptions": { "sourceType": "module" }
或代码中的 "use strict"
指令)的此规则的正确代码示例:
¥Examples of correct code for this rule with ES6 environment and strict mode via "parserOptions": { "sourceType": "module" }
in the ESLint configuration or "use strict"
directive in the code:
/*eslint no-lone-blocks: "error"*/
"use strict";
{
function foo() {}
}
版本
此规则是在 ESLint v0.4.0 中引入。