no-lone-blocks
禁用不必要的巢狀區塊
在 ES6 之前的 JavaScript 中,以大括號分隔的獨立程式碼區塊不會建立新的作用域,也沒有任何用途。例如,這些大括號對 foo
沒有任何作用
{
var foo = bar();
}
在 ES6 中,如果存在區塊級綁定(let
和 const
)、類別宣告或函式宣告(在嚴格模式下),程式碼區塊可能會建立新的作用域。在這些情況下,區塊不被認為是多餘的。
規則詳情
此規則旨在消除腳本頂層或其他區塊內不必要且可能令人困惑的區塊。
此規則的錯誤程式碼範例
在遊樂場中開啟
/*eslint no-lone-blocks: "error"*/
if (foo) {
bar();
}
function bar() {
}
class C {
static {
}
}
此規則的正確程式碼範例
在遊樂場中開啟
/*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 環境和嚴格模式下,此規則的正確程式碼範例
在遊樂場中開啟
/*eslint no-lone-blocks: "error"*/
"use strict";
{
function foo() {}
}
版本
此規則在 ESLint v0.4.0 中引入。