ESLint -- 禁止未使用过的变量 (no-unused-vars)

详细讲解请看no-unused-vars

配置文件代码:

    // disallow declaration of variables that are not used in the code
    'no-unused-vars': ['error', { 
        vars: 'local', //仅仅检测本作用域中声明的变量是否使用,允许不使用全局环境中的变量
        args: 'after-used', //最后一个参数被使用就不报错
        ignoreRestSiblings: true, //
}],

Rule Details

此规则旨在消除未使用过的变量,方法和方法中的参数名,当发现这些存在,发出警告。

符合下面条件的变量被认为是可以使用的:

  • 作为回调函数
  • 被读取 (var y = x)
  • 传入函数中作为argument对象(doSomething(x))
  • 在传入到另一个函数的函数中被读取 一个变量仅仅是被赋值为 (var x = 5) 或者是被声明过,则认为它是没被考虑使用。

错误 代码示例:

/*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);
}

正确 代码示例:

/*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);
> exported

在 CommonJS 或者 ECMAScript 模块外部,可用 var创建一个被其他模块代码引用的变量。你也可以用 /* exported variableName */ 注释快表明此变量已导出,因此此变量不会被认为是未被使用过的。

需要注意的是 /* exported */ 在下列情况下是无效的:

  • node 或 commonjs 环境
  • parserOptions.sourceType 是 module
  • ecmaFeatures.globalReturn 为 true

results matching ""

    No results matching ""