Index

no-unused-vars

禁止未使用的变量

Recommended

配置文件 中使用来自 @eslint/jsrecommended 配置可以启用此规则

💡 hasSuggestions

此规则报告的一些问题可通过编辑器 建议 手动修复

在代码中声明但未使用的变量很可能是由于重构不完整导致的错误。这些变量占用了代码空间,并可能让读者感到困惑。

🌐 Variables that are declared and not used anywhere in the code are most likely an error due to incomplete refactoring. Such variables take up space in the code and can lead to confusion by readers.

规则详情

🌐 Rule Details

该规则旨在消除未使用的变量、函数和函数参数。

🌐 This rule is aimed at eliminating unused variables, functions, and function parameters.

如果满足以下任一条件,则认为变量 foo 已被使用:

🌐 A variable foo is considered to be used if any of the following are true:

  • 它被称为(foo())或构造为(new foo()
  • 它被读作 (let bar = foo)
  • 它作为参数(doSomething(foo))传入函数中
  • 它在传递给另一个函数(doSomething(function() { foo(); }))的函数内部被读取

如果一个变量仅仅被声明(let foo = 5)或赋值(foo = 7),它不能被视为已使用。

🌐 A variable is not considered to be used if it is only ever declared (let foo = 5) or assigned to (foo = 7).

此规则的错误代码示例:

🌐 Examples of incorrect code for this rule:

在线运行
/*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"]);

符合此规则的正确代码示例:

🌐 Examples of correct code for this rule:

在线运行
/*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 */ 注释块来指明该变量正在被导出,因此不应被认为是未使用的。

🌐 In environments outside of CommonJS or ECMAScript modules, you may use var to create a global variable that may be used by other scripts. You can use the /* exported variableName */ comment block to indicate that this variable is being exported and therefore should not be considered unused.

请注意,/* exported */ 对以下任何内容都没有效果:

🌐 Note that /* exported */ has no effect for any of the following:

  • languageOptions.sourceTypemodule(默认)或 commonjs
  • languageOptions.parserOptions.ecmaFeatures.globalReturntrue

行注释 // exported variableName 将不起作用,因为 exported 不是特定于行的。

🌐 The line comment // exported variableName will not work as exported is not line-specific.

/* exported global_var */

var global_var = 42;

/* exported variableName */ 操作与 no-unused-vars正确代码示例:

🌐 Examples of correct code for /* exported variableName */ operation with no-unused-vars:

在线运行
/*eslint no-unused-vars: "error"*/
/* exported global_var */

var global_var = 42;

选项

🌐 Options

此规则接受一个参数,该参数可以是字符串或对象。字符串设置与 vars 属性的设置相同(如下所述)。

🌐 This rule takes one argument which can be a string or an object. The string settings are the same as those of the vars property (explained below).

默认情况下,该规则对捕获的错误和变量启用 all 选项,对参数启用 after-used

🌐 By default this rule is enabled with all option for caught errors and variables, and after-used for arguments.

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

vars

vars 选项有两个设置:

🌐 The vars option has two settings:

  • "all" 检查所有变量的使用情况,包括全局作用域中的变量。然而,它排除了被 argscaughtErrors 等其他选项指定的变量。这是默认设置。
  • "local" 允许全局作用域中的变量未被使用。

变量:本地

🌐 vars: local

适用于 { "vars": "local" } 选项的正确代码示例:

🌐 Examples of correct code for the { "vars": "local" } option:

在线运行
/*eslint no-unused-vars: ["error", { "vars": "local" }]*/
/*global some_unused_var */

some_unused_var = 42;

{ “vars”: “local” } 选项配合 “languageOptions”: { “sourceType”: “script” } 的正确代码示例:

🌐 Examples of correct code for the { "vars": "local" } option with "languageOptions": { "sourceType": "script" }:

在线运行
/*eslint no-unused-vars: ["error", { "vars": "local" }]*/

const foo = 42;

let bar;

let baz = 42;

var qux;

var quux = 42;

varsIgnorePattern

varsIgnorePattern 选项指定不检查使用情况的例外:名称与正则表达式模式匹配的变量。例如,名称包含 ignoredIgnored 的变量。然而,它排除了被其他选项如 argsIgnorePatterncaughtErrorsIgnorePattern 作用的变量。

🌐 The varsIgnorePattern option specifies exceptions not to check for usage: variables whose names match a regexp pattern. For example, variables whose names contain ignored or Ignored. However, it excludes variables targeted by other options like argsIgnorePattern and caughtErrorsIgnorePattern.

适用于 { "varsIgnorePattern": "[iI]gnored" } 选项的正确代码示例:

🌐 Examples of correct code for the { "varsIgnorePattern": "[iI]gnored" } option:

在线运行
/*eslint no-unused-vars: ["error", { "varsIgnorePattern": "[iI]gnored" }]*/

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

args

args 选项有三个设置:

🌐 The args option has three settings:

  • after-used - 将不检查最后使用的参数之前出现的未使用的位置参数,但将检查最后使用的参数之后的所有命名参数和所有位置参数。
  • all - 必须使用所有命名参数。
  • none - 不要检查参数。

参数:使用后

🌐 args: after-used

默认 { "args": "after-used" } 选项的错误代码示例:

🌐 Examples of incorrect code for the default { "args": "after-used" } option:

在线运行
/*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" } 选项的正确代码示例:

🌐 Examples of correct code for the default { "args": "after-used" } option:

在线运行
/*eslint no-unused-vars: ["error", {"args": "after-used"}]*/

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

参数:全部

🌐 args: all

针对 { "args": "all" } 选项的错误代码示例:

🌐 Examples of incorrect code for the { "args": "all" } option:

在线运行
/*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" } 选项的正确代码示例:

🌐 Examples of correct code for the { "args": "none" } option:

在线运行
/*eslint no-unused-vars: ["error", { "args": "none" }]*/

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

argsIgnorePattern

argsIgnorePattern 选项指定不检查使用情况的例外:名称与正则表达式模式匹配的参数。例如,名称以下划线开头的变量。

🌐 The argsIgnorePattern option specifies exceptions not to check for usage: arguments whose names match a regexp pattern. For example, variables whose names begin with an underscore.

适用于 { "argsIgnorePattern": "^_" } 选项的正确代码示例:

🌐 Examples of correct code for the { "argsIgnorePattern": "^_" } option:

在线运行
/*eslint no-unused-vars: ["error", { "argsIgnorePattern": "^_" }]*/

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

caughtErrors

caughtErrors 选项用于 catch 块参数的验证。

🌐 The caughtErrors option is used for catch block arguments validation.

它有两个设置:

🌐 It has two settings:

  • all - 必须使用所有命名参数。这是默认设置。
  • none - 不检查错误对象。

caughtErrors:全部

🌐 caughtErrors: all

不指定此选项等同于将其分配给 all

🌐 Not specifying this option is equivalent of assigning it to all.

针对 { "caughtErrors": "all" } 选项的错误代码示例:

🌐 Examples of incorrect code for the { "caughtErrors": "all" } option:

在线运行
/*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" } 选项的正确代码示例:

🌐 Examples of correct code for the { "caughtErrors": "none" } option:

在线运行
/*eslint no-unused-vars: ["error", { "caughtErrors": "none" }]*/

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

caughtErrorsIgnorePattern

caughtErrorsIgnorePattern 选项指定不检查使用的例外情况:捕获名称与正则表达式模式匹配的参数。例如,名称以字符串 ‘ignore’ 开头的变量。

🌐 The caughtErrorsIgnorePattern option specifies exceptions not to check for usage: catch arguments whose names match a regexp pattern. For example, variables whose names begin with a string ‘ignore’.

适用于 { "caughtErrorsIgnorePattern": "^ignore" } 选项的正确代码示例:

🌐 Examples of correct code for the { "caughtErrorsIgnorePattern": "^ignore" } option:

在线运行
/*eslint no-unused-vars: ["error", { "caughtErrors": "all", "caughtErrorsIgnorePattern": "^ignore" }]*/

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

destructuredArrayIgnorePattern

destructuredArrayIgnorePattern 选项指定不检查使用情况的例外:数组解构模式中名称匹配正则表达式模式的元素。例如,名称以下划线开头的变量。

🌐 The destructuredArrayIgnorePattern option specifies exceptions not to check for usage: elements of array destructuring patterns whose names match a regexp pattern. For example, variables whose names begin with an underscore.

适用于 { "destructuredArrayIgnorePattern": "^_" } 选项的正确代码示例:

🌐 Examples of correct code for the { "destructuredArrayIgnorePattern": "^_" } option:

在线运行
/*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 属性的兄弟属性将被忽略。

🌐 The ignoreRestSiblings option is a boolean (default: false). Using a Rest Property it is possible to “omit” properties from an object, but by default the sibling properties are marked as “unused”. With this option enabled the rest property’s siblings are ignored.

适用于 { "ignoreRestSiblings": true } 选项的正确代码示例:

🌐 Examples of correct code for the { "ignoreRestSiblings": true } option:

在线运行
/*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 时,此选项会忽略包含静态初始化块的类。

🌐 The ignoreClassWithStaticInitBlock option is a boolean (default: false). Static initialization blocks allow you to initialize static variables and execute code during the evaluation of a class definition, meaning the static block code is executed without creating a new instance of the class. When set to true, this option ignores classes containing static initialization blocks.

“{ “ignoreClassWithStaticInitBlock”: true }”选项的错误代码示例

🌐 Examples of incorrect code for the { "ignoreClassWithStaticInitBlock": true } option

在线运行
/*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 } 选项的正确代码示例

🌐 Examples of correct code for the { "ignoreClassWithStaticInitBlock": true } option

在线运行
/*eslint no-unused-vars: ["error", { "ignoreClassWithStaticInitBlock": true }]*/

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

        console.log(bar);
    }
}

ignoreUsingDeclarations

ignoreUsingDeclarations 选项是布尔类型(默认值:false)。显式资源管理允许通过在变量作用域结束时隐式调用 Symbol.disposeSymbol.asyncDispose 方法来自动清理可释放资源。当此选项设置为 true 时,该规则会忽略使用 usingawait using 声明的变量。

🌐 The ignoreUsingDeclarations option is a boolean (default: false). Explicit resource management allows automatic teardown of disposables by calling Symbol.dispose or Symbol.asyncDispose method implicitly at the end of the variable’s scope. When this option is set to true, this rule ignores variables declared with using or await using.

针对 { "ignoreUsingDeclarations": true } 选项的错误代码示例:

🌐 Examples of incorrect code for the { "ignoreUsingDeclarations": true } option:

在线运行
/*eslint no-unused-vars: ["error", { "ignoreUsingDeclarations": true }]*/
const resource = getResource();

适用于 { "ignoreUsingDeclarations": true } 选项的正确代码示例:

🌐 Examples of correct code for the { "ignoreUsingDeclarations": true } option:

在线运行
/*eslint no-unused-vars: ["error", { "ignoreUsingDeclarations": true }]*/

using syncResource = getSyncResource();
await using asyncResource = getAsyncResource();

reportUsedIgnorePattern

reportUsedIgnorePattern 选项是一个布尔值(默认值:false)。使用此选项将报告任何匹配有效忽略模式选项(varsIgnorePatternargsIgnorePatterncaughtErrorsIgnorePatterndestructuredArrayIgnorePattern)的变量,如果它们已被使用。

🌐 The reportUsedIgnorePattern option is a boolean (default: false). Using this option will report variables that match any of the valid ignore pattern options (varsIgnorePattern, argsIgnorePattern, caughtErrorsIgnorePattern, or destructuredArrayIgnorePattern) if they have been used.

针对 { "reportUsedIgnorePattern": true } 选项的错误代码示例:

🌐 Examples of incorrect code for the { "reportUsedIgnorePattern": true } option:

在线运行
/*eslint no-unused-vars: ["error", { "reportUsedIgnorePattern": true, "varsIgnorePattern": "[iI]gnored" }]*/

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

适用于 { "reportUsedIgnorePattern": true } 选项的正确代码示例:

🌐 Examples of correct code for the { "reportUsedIgnorePattern": true } option:

在线运行
/*eslint no-unused-vars: ["error", { "reportUsedIgnorePattern": true, "varsIgnorePattern": "[iI]gnored" }]*/

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

何时不使用

🌐 When Not To Use It

如果你不想收到有关未使用的变量或函数参数的通知,你可以安全地关闭此规则。

🌐 If you don’t want to be notified about unused variables or function arguments, you can safely turn this rule off.

版本

此规则是在 ESLint v0.0.9 中引入。

资源