版本

no-lone-blocks

不允許不必要的巢狀區塊

在 ES6 之前的 JavaScript 中,以大括號分隔的獨立程式碼區塊不會建立新的作用域,也沒有任何用處。例如,這些大括號對 foo 沒有任何作用

{
    var foo = bar();
}

在 ES6 中,如果存在區塊級別綁定 (letconst)、類別宣告或函式宣告(在嚴格模式下),程式碼區塊可能會建立新的作用域。在這些情況下,區塊不被視為多餘。

規則詳情

此規則旨在消除腳本頂層或其他區塊內不必要且可能令人困惑的區塊。

此規則的錯誤程式碼範例

在 Playground 中開啟
/*eslint no-lone-blocks: "error"*/

{}

if (foo) {
    bar();
    {
        baz();
    }
}

function bar() {
    {
        baz();
    }
}

{
    function foo() {}
}

{
    aLabel: {
    }
}

class C {
    static {
        {
            foo();
        }
    }
}

此規則的正確程式碼範例

在 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 中引入。

資源

變更語言