版本

no-unused-vars

禁止未使用的變數

建議

設定檔中使用 @eslint/jsrecommended 設定會啟用此規則

💡 有建議

此規則回報的某些問題可以透過編輯器的建議手動修正

在程式碼中宣告但未在任何地方使用的變數,很可能是由於不完整的重構而造成的錯誤。 這些變數會佔用程式碼空間,並可能導致讀者混淆。

規則詳細資訊

此規則旨在消除未使用的變數、函式和函式參數。

如果符合以下任何條件,則變數 foo 會被視為已使用

  • 它被呼叫 (foo()) 或建構 (new foo())
  • 它被讀取 (let bar = foo)
  • 它作為引數傳遞到函式中 (doSomething(foo))
  • 它在傳遞到另一個函式的函式內部被讀取 (doSomething(function() { foo(); }))

如果變數僅被宣告 (let foo = 5) 或賦值 (foo = 7),則會被視為已使用。

此規則的錯誤程式碼範例

在 Playground 中開啟
/*eslint no-unused-vars: "error"*/
/*global some_unused_var*/

// It checks variables you have defined as global
some_unused_var = 42;

let x;

// Write-only variables are not considered as used.
let y = 10;
y = 5;

// A read for a modification of itself is not considered as used.
let z = 0;
z = z + 1;

// By default, unused arguments cause warnings.
(function(foo) {
    return 5;
})();

// Unused recursive functions also cause warnings.
function fact(n) {
    if (n < 2) return 1;
    return n * fact(n - 1);
}

// When a function definition destructures an array, unused entries from the array also cause warnings.
function getY([x, y]) {
    return y;
}
getY(["a", "b"]);

此規則的正確程式碼範例

在 Playground 中開啟
/*eslint no-unused-vars: "error"*/

const x = 10;
alert(x);

// foo is considered used here
myFunc(function foo() {
    // ...
}.bind(this));

(function(foo) {
    return foo;
})();

var myFunc;
myFunc = setTimeout(function() {
    // myFunc is considered used
    myFunc();
}, 50);

// Only the second argument from the destructured array is used.
function getY([, y]) {
    return y;
}
getY(["a", "b"]);

exported

在 CommonJS 或 ECMAScript 模組之外的環境中,您可以使用 var 建立可供其他腳本使用的全域變數。 您可以使用 /* exported variableName */ 註解區塊來指示此變數正在匯出,因此不應被視為未使用。

請注意,/* exported */ 對於以下任何情況均無效

  • languageOptions.sourceTypemodule (預設) 或 commonjs
  • languageOptions.parserOptions.ecmaFeatures.globalReturntrue

行註解 // exported variableName 將不起作用,因為 exported 不是特定於行的。

/* exported global_var */

var global_var = 42;

搭配 no-unused-vars/* exported variableName */ 操作的正確程式碼範例

在 Playground 中開啟
/*eslint no-unused-vars: "error"*/
/* exported global_var */

var global_var = 42;

選項

此規則接受一個引數,它可以是字串或物件。 字串設定與 vars 屬性的設定相同(如下所述)。

預設情況下,此規則啟用,對捕獲的錯誤和變數使用 all 選項,對引數使用 after-used

{
    "rules": {
        "no-unused-vars": ["error", {
            "vars": "all",
            "args": "after-used",
            "caughtErrors": "all",
            "ignoreRestSiblings": false,
            "reportUsedIgnorePattern": false
        }]
    }
}

vars

vars 選項有兩個設定

  • all 檢查所有變數的使用情況,包括全域範圍內的變數。 但是,它排除以其他選項(如 argscaughtErrors)為目標的變數。 這是預設設定。
  • local 僅檢查本地宣告的變數是否被使用,但允許全域變數未被使用。

vars: local

{ \"vars\": \"local\" } 選項的正確程式碼範例

在 Playground 中開啟
/*eslint no-unused-vars: ["error", { "vars": "local" }]*/
/*global some_unused_var */

some_unused_var = 42;

varsIgnorePattern

varsIgnorePattern 選項指定不檢查使用情況的例外:名稱與 regexp 模式匹配的變數。 例如,名稱包含 ignoredIgnored 的變數。 但是,它排除以其他選項(如 argsIgnorePatterncaughtErrorsIgnorePattern)為目標的變數。

{ \"varsIgnorePattern\": \"[iI]gnored\" } 選項的正確程式碼範例

在 Playground 中開啟
/*eslint no-unused-vars: ["error", { "varsIgnorePattern": "[iI]gnored" }]*/

const firstVarIgnored = 1;
const secondVar = 2;
console.log(secondVar);

args

args 選項有三個設定

  • after-used - 未使用的位置引數,如果出現在最後使用的引數之前,將不會被檢查,但所有具名引數和最後使用的引數之後的所有位置引數都將被檢查。
  • all - 必須使用所有具名引數。
  • none - 不檢查引數。

args: after-used

預設 { \"args\": \"after-used\" } 選項的錯誤程式碼範例

在 Playground 中開啟
/*eslint no-unused-vars: ["error", { "args": "after-used" }]*/

// 2 errors, for the parameters after the last used parameter (bar)
// "baz" is defined but never used
// "qux" is defined but never used
(function(foo, bar, baz, qux) {
    return bar;
})();

預設 { \"args\": \"after-used\" } 選項的正確程式碼範例

在 Playground 中開啟
/*eslint no-unused-vars: ["error", {"args": "after-used"}]*/

(function(foo, bar, baz, qux) {
    return qux;
})();

args: all

{ \"args\": \"all\" } 選項的錯誤程式碼範例

在 Playground 中開啟
/*eslint no-unused-vars: ["error", { "args": "all" }]*/

// 2 errors
// "foo" is defined but never used
// "baz" is defined but never used
(function(foo, bar, baz) {
    return bar;
})();

args: none

{ \"args\": \"none\" } 選項的正確程式碼範例

在 Playground 中開啟
/*eslint no-unused-vars: ["error", { "args": "none" }]*/

(function(foo, bar, baz) {
    return bar;
})();

argsIgnorePattern

argsIgnorePattern 選項指定不檢查使用情況的例外:名稱與 regexp 模式匹配的引數。 例如,名稱以下底線開頭的變數。

{ \"argsIgnorePattern\": \"^_\" } 選項的正確程式碼範例

在 Playground 中開啟
/*eslint no-unused-vars: ["error", { "argsIgnorePattern": "^_" }]*/

function foo(x, _y) {
    return x + 1;
}
foo();

caughtErrors

caughtErrors 選項用於 catch 區塊引數驗證。

它有兩個設定

  • all - 必須使用所有具名引數。 這是預設設定。
  • none - 不檢查錯誤物件。

caughtErrors: all

未指定此選項等同於將其設定為 all

{ \"caughtErrors\": \"all\" } 選項的錯誤程式碼範例

在 Playground 中開啟
/*eslint no-unused-vars: ["error", { "caughtErrors": "all" }]*/

// 1 error
// "err" is defined but never used
try {
    //...
} catch (err) {
    console.error("errors");
}

caughtErrors: none

{ \"caughtErrors\": \"none\" } 選項的正確程式碼範例

在 Playground 中開啟
/*eslint no-unused-vars: ["error", { "caughtErrors": "none" }]*/

try {
    //...
} catch (err) {
    console.error("errors");
}

caughtErrorsIgnorePattern

caughtErrorsIgnorePattern 選項指定不檢查使用情況的例外:名稱與 regexp 模式匹配的 catch 引數。 例如,名稱以字串 'ignore' 開頭的變數。

{ \"caughtErrorsIgnorePattern\": \"^ignore\" } 選項的正確程式碼範例

在 Playground 中開啟
/*eslint no-unused-vars: ["error", { "caughtErrors": "all", "caughtErrorsIgnorePattern": "^ignore" }]*/

try {
    //...
} catch (ignoreErr) {
    console.error("errors");
}

destructuredArrayIgnorePattern

destructuredArrayIgnorePattern 選項指定不檢查使用情況的例外:名稱與 regexp 模式匹配的陣列解構模式的元素。 例如,名稱以下底線開頭的變數。

{ \"destructuredArrayIgnorePattern\": \"^_\" } 選項的正確程式碼範例

在 Playground 中開啟
/*eslint no-unused-vars: ["error", { "destructuredArrayIgnorePattern": "^_" }]*/

const [a, _b, c] = ["a", "b", "c"];
console.log(a+c);

const { x: [_a, foo] } = bar;
console.log(foo);

function baz([_c, x]) {
    x;
}
baz();

function test({p: [_q, r]}) {
    r;
}
test();

let _m, n;
foo.forEach(item => {
    [_m, n] = item;
    console.log(n);
});

let _o, p;
_o = 1;
[_o, p] = foo;
p;

ignoreRestSiblings

ignoreRestSiblings 選項是一個布林值(預設值:false)。 使用 Rest Property 可以「省略」物件的屬性,但預設情況下,同層級屬性會標記為「未使用」。 啟用此選項後,rest 屬性的同層級屬性將被忽略。

{ \"ignoreRestSiblings\": true } 選項的正確程式碼範例

在 Playground 中開啟
/*eslint no-unused-vars: ["error", { "ignoreRestSiblings": true }]*/

// 'foo' and 'bar' were ignored because they have a rest property sibling.
const { foo, ...rest } = data;
console.log(rest);

// OR

let bar;
({ bar, ...rest } = data);

ignoreClassWithStaticInitBlock

ignoreClassWithStaticInitBlock 選項是一個布林值(預設值:false)。 靜態初始化區塊允許您在評估類別定義期間初始化靜態變數並執行程式碼,這表示靜態區塊程式碼在不建立類別新實例的情況下執行。 當設定為 true 時,此選項會忽略包含靜態初始化區塊的類別。

{ \"ignoreClassWithStaticInitBlock\": true } 選項的錯誤程式碼範例

在 Playground 中開啟
/*eslint no-unused-vars: ["error", { "ignoreClassWithStaticInitBlock": true }]*/

class Foo {
    static myProperty = "some string";
    static mymethod() {
        return "some string";
    }
}

class Bar {
    static {
        let baz; // unused variable
    }
}

{ \"ignoreClassWithStaticInitBlock\": true } 選項的正確程式碼範例

在 Playground 中開啟
/*eslint no-unused-vars: ["error", { "ignoreClassWithStaticInitBlock": true }]*/

class Foo {
    static {
        let bar = "some string";

        console.log(bar);
    }
}

reportUsedIgnorePattern

reportUsedIgnorePattern 選項是一個布林值(預設值:false)。 使用此選項將會回報符合任何有效忽略模式選項(varsIgnorePatternargsIgnorePatterncaughtErrorsIgnorePatterndestructuredArrayIgnorePattern)的變數(如果它們已被使用)。

{ \"reportUsedIgnorePattern\": true } 選項的錯誤程式碼範例

在 Playground 中開啟
/*eslint no-unused-vars: ["error", { "reportUsedIgnorePattern": true, "varsIgnorePattern": "[iI]gnored" }]*/

const firstVarIgnored = 1;
const secondVar = 2;
console.log(firstVarIgnored, secondVar);

{ \"reportUsedIgnorePattern\": true } 選項的正確程式碼範例

在 Playground 中開啟
/*eslint no-unused-vars: ["error", { "reportUsedIgnorePattern": true, "varsIgnorePattern": "[iI]gnored" }]*/

const firstVar = 1;
const secondVar = 2;
console.log(firstVar, secondVar);

何時不該使用

如果您不想收到有關未使用變數或函式引數的通知,您可以安全地關閉此規則。

版本

此規則在 ESLint v0.0.9 中引入。

資源

變更語言