no-unused-vars

禁止未使用的变量

Recommended

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

由于重构不完整,已声明但未在代码中任何地方使用的变量很可能是错误。这样的变量会占用代码中的空间,并可能导致读者混淆。

¥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()

    ¥It is called (foo()) or constructed (new foo())

  • 读取 (var bar = foo)

    ¥It is read (var bar = foo)

  • 它作为参数传递给函数(doSomething(foo)

    ¥It is passed into a function as an argument (doSomething(foo))

  • 它在传递给另一个函数(doSomething(function() { foo(); }))的函数内部读取

    ¥It is read inside of a function that is passed to another function (doSomething(function() { foo(); }))

如果变量只被声明(var foo = 5)或分配给(foo = 7),则不认为它被使用。

¥A variable is not considered to be used if it is only ever declared (var 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;

var x;

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

// A read for a modification of itself is not considered as used.
var 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"*/

var 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:

  • 环境为 nodecommonjs

    ¥when the environment is node or commonjs

  • parserOptions.sourceTypemodule

    ¥when parserOptions.sourceType is module

  • ecmaFeatures.globalReturntrue

    ¥when ecmaFeatures.globalReturn is true

行注释 // 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,
            "reportUsedIgnorePattern": false
        }]
    }
}

vars

vars 选项有两个设置:

¥The vars option has two settings:

  • all 检查所有变量的使用情况,包括全局作用域内的变量。但是,它排除了其他选项(例如 argscaughtErrors)所针对的变量。这是默认设置。

    ¥all checks all variables for usage, including those in the global scope. However, it excludes variables targeted by other options like args and caughtErrors. This is the default setting.

  • local 仅检查是否使用了局部声明的变量,但允许未使用全局变量。

    ¥local checks only that locally-declared variables are used but will allow global variables to be unused.

变量: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;

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" }]*/

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

args

args 选项具有三个设置:

¥The args option has three settings:

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

    ¥after-used - unused positional arguments that occur before the last used argument will not be checked, but all named arguments and all positional arguments after the last used argument will be checked.

  • all - 必须使用所有命名参数。

    ¥all - all named arguments must be used.

  • none - 不要检查参数。

    ¥none - do not check arguments.

参数:after-used

¥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;
})();

参数:all

¥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;
})();

参数:none

¥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 - 必须使用所有命名参数。这是默认设置。

    ¥all - all named arguments must be used. This is the default setting.

  • none - 不检查错误对象。

    ¥none - do not check error objects.

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)。使用 剩余属性 可以从对象中获得 “omit” 属性,但默认情况下,兄弟属性被标记为 “unused”。启用此选项后,其余属性的兄弟姐妹将被忽略。

¥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.
var { foo, ...rest } = data;
console.log(rest);

// OR

var 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);
    }
}

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" }]*/

var firstVarIgnored = 1;
var 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" }]*/

var firstVar = 1;
var 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 中引入。

资源