Error store is assigned a value but never used no unused vars

A pluggable and configurable linter tool for identifying and reporting on patterns in JavaScript. Maintain your code quality with ease.

Disallow unused variables

Recommended

The "extends": "eslint:recommended" property in a configuration file enables this rule

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.

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

  • It is called (foo()) or constructed (new foo())
  • It is read (var bar = foo)
  • It is passed into a function as an argument (doSomething(foo))
  • It is read inside of a function that is passed to another function (doSomething(function() { foo(); }))

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

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

exported

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.

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

  • when the environment is node or commonjs
  • when parserOptions.sourceType is module
  • when ecmaFeatures.globalReturn is true

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

Examples of correct code for /* exported variableName */ operation:

/* exported global_var */

var global_var = 42;

Options

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).

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

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

vars

The vars option has two settings:

  • all checks all variables for usage, including those in the global scope. This is the default setting.
  • local checks only that locally-declared variables are used but will allow global variables to be unused.

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

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.

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

The args option has three settings:

  • 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 named arguments must be used.
  • none — do not check arguments.

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

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

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

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

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

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

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.

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

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

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

caughtErrors

The caughtErrors option is used for catch block arguments validation.

It has two settings:

  • none — do not check error objects. This is the default setting.
  • all — all named arguments must be used.

caughtErrors: none

Not specifying this rule is equivalent of assigning it to none.

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

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

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

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

caughtErrorsIgnorePattern

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’.

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

/*eslint no-unused-vars: ["error", { "caughtErrorsIgnorePattern": "^ignore" }]*/

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

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.

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

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.

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, ...coords } = data;

var bar;
({ bar, ...coords } = data);

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.

Version

This rule was introduced in ESLint v0.0.9.

Resources

  • Rule source
  • Tests source

Aug 3, 2020

Rules are the fundamental building block for ESLint. Every ESLint configuration
is a collection of rules and how strictly those rules are enforced.
Even Standard is implemented as a collection of ESLint rules.

For example, below is a minimal ESLint config .eslintrc.json file that makes ESLint error out if there are unused
variables. Every ESLint rule has a name: this rule is called no-unused-vars. Here’s the documentation for no-unused-vars.

{
  "parserOptions": {
    "ecmaVersion": 2020
  },
  "rules": {
    "no-unused-vars": "error"
  }
}

Suppose you have the below one-line script test.js in the same folder as .eslintrc.json. The message variable is never used.

const message = 'Hello, World!';

You can then run ESLint using ./node_modules/.bin/eslint ./test.js, and get the below output.

$ ./node_modules/.bin/eslint ./test.js 

/scratch/test.js
  1:7  error  'message' is assigned a value but never used  no-unused-vars

✖ 1 problem (1 error, 0 warnings)

$ 

Error vs Warning

The "no-unused-vars": "error" line tells ESLint that unused variables should cause the linter to fail. ESLint also
supports making a rule a warning as opposed to an error.
ESLint will still succeed if the only rule violations are warnings.

For example, below is how you make the no-unused-vars rule a warning rather than an error.

{
  "parserOptions": {
    "ecmaVersion": 2020
  },
  "rules": {
    "no-unused-vars": "warn"
  }
}

Run ESLint with the above configuration on test.js, and you’ll get a warning rather than an error.

$ ./node_modules/.bin/eslint ./test.js 

/scratch/test.js
  1:7  warning  'message' is assigned a value but never used  no-unused-vars

✖ 1 problem (0 errors, 1 warning)

$ echo $?
0
$ 

The echo $? command is how you get the exit code of the last command in Linux. Exit code 0 means that the command succeeded, so eslint succeeded even though there were warnings.

More Complex Rules

The no-unused-vars rule doesn’t leave much room for configuration: either a variable is unused, or it isn’t.
A more interesting rule is the max-len rule, which enforces the maximum
length of a line.

By default, setting "max-len": "error" will cause ESLint to error out if there’s a line with more than 80 characters.
However, you can configure this by setting max-len to an array, where the 2nd element in the array is an options
object that configures max-len. Below is a .eslintrc.json that tells ESLint to error out if a line is longer
than 66 characters.

{
  "parserOptions": {
    "ecmaVersion": 2020
  },
  "rules": {
    "max-len": ["error", { "code": 66 }]
  }
}

Suppose test.js contains one line that’s 77 characters long:

const message = 'This long string makes this line longer than 66 characters';

Running ESLint on the above file will report an error:

$ ./node_modules/.bin/eslint ./test.js 

/scratch/test.js
  1:1  error  This line has a length of 77. Maximum allowed is 66  max-len

✖ 1 problem (1 error, 0 warnings)

$ 

Custom Rules from npm

ESLint has a wide variety of built-in rules, but you can also find new
rules on npm. Many ESLint plugins provide additional rules for working with specific libraries and frameworks.

For example, eslint-plugin-vue provides extra Vue-specific
rules. Run npm install eslint-plugin-vue and add a plugins list to your .eslintrc.json. Once you do that,
you get access to Vue-specific rules like no-async-in-computed-properties.

{
  "parserOptions": {
    "ecmaVersion": 2020
  },
  "plugins": ["eslint-plugin-vue"],
  "rules": {
    "vue/no-async-in-computed-properties": "error"
  }
}

If you run ESLint on the below test.js file, the vue/no-async-in-computed-properties rule will error out because
badProperty is set to an async function:

const Vue = require('vue');

module.exports = Vue.component('bad-component', {
  template: '<h1>Hello</h1>',
  computed: {
    badProperty: async function() { return 42; }
  }
});
$ ./node_modules/.bin/eslint ./test.js 

/scratch/test.js
  6:18  error  Unexpected async function declaration in "badProperty" computed property  vue/no-async-in-computed-properties

✖ 1 problem (1 error, 0 warnings)

$ 

More Eslint Tutorials

  • Using ESLint’s —fix Flag
  • Intro to ESLint Config Files
  • Disable ESLint for a Single Line
  • Ignore Lines and Files In ESLint

Содержание

  1. no-unused-vars
  2. Rule Details
  3. exported
  4. Options
  5. vars: local
  6. varsIgnorePattern
  7. args: after-used
  8. args: all
  9. args: none
  10. argsIgnorePattern
  11. caughtErrors
  12. caughtErrors: none
  13. caughtErrors: all
  14. caughtErrorsIgnorePattern
  15. destructuredArrayIgnorePattern
  16. ignoreRestSiblings
  17. When Not To Use It
  18. ‘React’ is defined but never used no-unused-vars #11183
  19. Comments
  20. no-unused-vars
  21. Как отключить правило ESLint?
  22. Как обойти ESLint?
  23. Как запустить автоисправление ESLint?
  24. Как автоматически удалять неиспользуемый импорт?
  25. Как избавиться от неиспользуемого импорта?
  26. Как удалить все неиспользуемые импорты в react?
  27. Как отключить Vscode ESLint?
  28. Rule Details
  29. exported
  30. Options
  31. vars: local
  32. varsIgnorePattern
  33. args: after-used
  34. args: all
  35. args: none
  36. ignoreRestSiblings
  37. argsIgnorePattern
  38. destructuredArrayIgnorePattern
  39. caughtErrors
  40. caughtErrors: none
  41. caughtErrors: all
  42. caughtErrorsIgnorePattern
  43. Когда не использовать его

no-unused-vars

Disallow unused variables

The «extends»: «eslint:recommended» property in a configuration file enables this rule

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.

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

  • It is called ( foo() ) or constructed ( new foo() )
  • It is read ( var bar = foo )
  • It is passed into a function as an argument ( doSomething(foo) )
  • It is read inside of a function that is passed to another function ( doSomething(function() < foo(); >) )

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:

Examples of correct code for this rule:

exported

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.

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

  • when the environment is node or commonjs
  • when parserOptions.sourceType is module
  • when ecmaFeatures.globalReturn is true

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

Examples of correct code for /* exported variableName */ operation:

Options

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).

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

The vars option has two settings:

  • all checks all variables for usage, including those in the global scope. This is the default setting.
  • local checks only that locally-declared variables are used but will allow global variables to be unused.

vars: local

Examples of correct code for the < «vars»: «local» >option:

varsIgnorePattern

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 .

Examples of correct code for the < «varsIgnorePattern»: «[iI]gnored» >option:

The args option has three settings:

  • 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 named arguments must be used.
  • none — do not check arguments.

args: after-used

Examples of incorrect code for the default < «args»: «after-used» >option:

Examples of correct code for the default < «args»: «after-used» >option:

args: all

Examples of incorrect code for the < «args»: «all» >option:

args: none

Examples of correct code for the < «args»: «none» >option:

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.

Examples of correct code for the < «argsIgnorePattern»: «^_» >option:

caughtErrors

The caughtErrors option is used for catch block arguments validation.

It has two settings:

  • none — do not check error objects. This is the default setting.
  • all — all named arguments must be used.

caughtErrors: none

Not specifying this rule is equivalent of assigning it to none .

Examples of correct code for the < «caughtErrors»: «none» >option:

caughtErrors: all

Examples of incorrect code for the < «caughtErrors»: «all» >option:

caughtErrorsIgnorePattern

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’.

Examples of correct code for the < «caughtErrorsIgnorePattern»: «^ignore» >option:

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.

Examples of correct code for the < «destructuredArrayIgnorePattern»: «^_» >option:

ignoreRestSiblings

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.

Examples of correct code for the < «ignoreRestSiblings»: true >option:

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.

Источник

‘React’ is defined but never used no-unused-vars #11183

When i run eslint on my code, I get the error:
‘React’ is defined but never used no-unused-vars
when I remove import ‘React’ from ‘react’ I get the error
‘React’ must be in scope when using JSX

I tried enabling the rules below but still receive the error.
«react/jsx-uses-react»: 1,
«react/jsx-uses-vars»: 1,
«react/react-in-jsx-scope»: 1

Can someone help me check if my configurations are correct, if I’m not overriding anything?

I am using these versions in package.json:
devDependencies

The text was updated successfully, but these errors were encountered:

Hi @VanessaChu, thanks for the issue.

Your configuration looks good to me. Would you mind trying to run ESLint with the —debug flag to see if another configuration is being picked up unexpectedly?

@VanessaChu I’m guessing that you are describing code that looks like this:

I think that the rules configuration might not work in this scenario. However, the rules you are working with are from a plugin called eslint-plugin-react , so I’m not really familiar with how they are supposed to work. I would suggest contacting the plugin authors: https://github.com/yannickcr/eslint-plugin-react/issues

You might need to enable the react/jsx-uses-react rule.

@platinumazure after running npm run lint —debug
Lifecycle scripts included:
test
jest

available via npm run-script :
build
npm run copy-src
copy-src
(cd build && mkdir -p lib/commonjs/story-builder) && cp -r src/* package.json build/lib/commonjs/story-builder
clean
cd build && rm -r lib/commonjs/story-builder
release
npm run lint && npm run build && npm run test
test-watch
jest —watch
test-debug
node —inspect-brk node_modules/.bin/jest —runInBand
lint
node node_modules/.bin/eslint src/ test/ —fix

@not-an-aardvark I have already enabled react/jsx-uses-react with «react/jsx-uses-react»: 1,

My apologies, I didn’t realize you were running an npm script. Adding just —debug to an npm script results in npm’s debug logs being visible, rather than ESLint’s.

Could you try running the script with — —debug on the end? This ensures the —debug parameter is passed to ESLint rather than consumed by npm. Thanks!

@VanessaChu Does your code contain valid JSX?

Unfortunately, it looks like there wasn’t enough interest from the team
or community to implement this change. While we wish we’d be able to
accommodate everyone’s requests, we do need to prioritize. We’ve found
that issues failing to reach accepted status after 21 days tend to
never be accepted, and as such, we close those issues.
This doesn’t mean the idea isn’t interesting or useful, just that it’s
not something the team can commit to.

Thanks for contributing to ESLint and we appreciate your understanding.

Источник

no-unused-vars

Запретить неиспользуемые переменные

Как отключить правило ESLint?

Как обойти ESLint?

Как запустить автоисправление ESLint?

Как автоматически удалять неиспользуемый импорт?

Как избавиться от неиспользуемого импорта?

Как удалить все неиспользуемые импорты в react?

Как отключить Vscode ESLint?

«extends»: «eslint:recommended» property in a configuration file enables this rule’ onmousemove=»i18n(this)»>Свойство «extends»: «eslint:recommended» в файле конфигурации включает это правило .

Переменные,которые объявлены и нигде не используются в коде,скорее всего,являются ошибкой из-за неполного рефакторинга.Такие переменные занимают место в коде и могут привести к путанице у читателей.

Rule Details

Данное правило направлено на устранение неиспользуемых переменных,функций и параметров функции.

foo is considered to be used if any of the following are true:» onmousemove=»i18n(this)»>Переменная foo считается использованной, если выполняется одно из следующих условий:

  • foo() ) or constructed ( new foo() )» onmousemove=»i18n(this)»>Он называется ( foo() ) или сконструирован ( new foo() )
  • var bar = foo )» onmousemove=»i18n(this)»>Читается ( var bar = foo )
  • doSomething(foo) )» onmousemove=»i18n(this)»>Он передается в функцию как аргумент ( doSomething(foo) )
  • doSomething(function() < foo(); >) )» onmousemove=»i18n(this)»>Он читается внутри функции, которая передается другой функции ( doSomething(function() < foo(); >) )

var foo = 5 ) or assigned to ( foo = 7 ).» onmousemove=»i18n(this)»>Переменная не считается использованной, если она только когда-либо была объявлена ​​( var foo = 5 ) или присвоена ( foo = 7 ).

Примеры неправильного кода для этого правила:

Примеры правильного кода для этого правила:

exported

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.» onmousemove=»i18n(this)»>В средах за пределами модулей CommonJS или ECMAScript вы можете использовать var для создания глобальной переменной, которая может использоваться другими скриптами. Вы можете использовать блок комментариев /* exported variableName */ чтобы указать, что эта переменная экспортируется и, следовательно, не должна считаться неиспользованной.

/* exported */ has no effect for any of the following:» onmousemove=»i18n(this)»>Обратите внимание, что /* exported */ не влияет ни на одно из следующего:

  • node or commonjs » onmousemove=»i18n(this)»>когда среда является node или commonjs
  • parserOptions.sourceType is module » onmousemove=»i18n(this)»>когда parserOptions.sourceType является module
  • ecmaFeatures.globalReturn is true » onmousemove=»i18n(this)»>когда ecmaFeatures.globalReturn является true

// exported variableName will not work as exported is not line-specific.» onmousemove=»i18n(this)»>Комментарий к строке // exported variableName не будет работать, так как exported строка не зависит от конкретной строки.

/* exported variableName */ operation:» onmousemove=»i18n(this)»>Примеры правильного кода для операции /* exported variableName */ :

Options

vars property (explained below).» onmousemove=»i18n(this)»>Это правило принимает один аргумент, который может быть строкой или объектом. Настройки строки такие же, как у свойства vars (объяснено ниже).

all option for variables and after-used for arguments.» onmousemove=»i18n(this)»>По умолчанию это правило включено со all параметрами для переменных и after-used для аргументов.

vars option has two settings:» onmousemove=»i18n(this)»>Опция vars имеет две настройки:

  • all checks all variables for usage, including those in the global scope. This is the default setting.» onmousemove=»i18n(this)»> all проверяет все переменные на предмет использования, в том числе в глобальной области. Это значение по умолчанию.
  • local checks only that locally-declared variables are used but will allow global variables to be unused.» onmousemove=»i18n(this)»> local проверяет только то, что используются локально объявленные переменные, но допускает неиспользование глобальных переменных.

vars: local

< «vars»: «local» >option:’ onmousemove=»i18n(this)»>Примеры правильного кода для параметра < «vars»: «local» >:

varsIgnorePattern

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 .» onmousemove=»i18n(this)»>Параметр varsIgnorePattern указывает исключения, которые не следует проверять на использование: переменные, имена которых соответствуют шаблону регулярного выражения. Например, переменные, имена которых содержат ignored или Ignored .

< «varsIgnorePattern»: «[iI]gnored» >option:’ onmousemove=»i18n(this)»>Примеры правильного кода для параметра < «varsIgnorePattern»: «[iI]gnored» >:

args option has three settings:» onmousemove=»i18n(this)»>Параметр args имеет три настройки:

  • 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.» onmousemove=»i18n(this)»> after-used — неиспользуемые позиционные аргументы, которые встречаются перед последним использованным аргументом, не будут проверяться, но будут проверены все именованные аргументы и все позиционные аргументы после последнего использованного аргумента.
  • all — all named arguments must be used.» onmousemove=»i18n(this)»> all — должны использоваться все именованные аргументы.
  • none — do not check arguments.» onmousemove=»i18n(this)»> none — не проверять аргументы.

args: after-used

< «args»: «after-used» >option:’ onmousemove=»i18n(this)»>Примеры неправильного кода для параметра по умолчанию < «args»: «after-used» >:

< «args»: «after-used» >option:’ onmousemove=»i18n(this)»>Примеры правильного кода для опции по умолчанию < «args»: «after-used» >:

args: all

< «args»: «all» >option:’ onmousemove=»i18n(this)»>Примеры неправильного кода для параметра < «args»: «all» >:

args: none

< «args»: «none» >option:’ onmousemove=»i18n(this)»>Примеры правильного кода для параметра < «args»: «none» >:

ignoreRestSiblings

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.’ onmousemove=»i18n(this)»>Параметр ignoreRestSiblings является логическим (по умолчанию: false ). Используя Rest Property , можно «опустить» свойства объекта, но по умолчанию родственные свойства помечаются как «неиспользуемые». Если эта опция включена, соседние элементы остальных свойств игнорируются.

< «ignoreRestSiblings»: true >option:’ onmousemove=»i18n(this)»>Примеры правильного кода для параметра < «ignoreRestSiblings»: true >:

argsIgnorePattern

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.» onmousemove=»i18n(this)»>Параметр argsIgnorePattern указывает исключения, которые не следует проверять на использование: аргументы, имена которых соответствуют шаблону регулярного выражения. Например, переменные, имена которых начинаются с подчеркивания.

< «argsIgnorePattern»: «^_» >option:’ onmousemove=»i18n(this)»>Примеры правильного кода для параметра < «argsIgnorePattern»: «^_» >:

destructuredArrayIgnorePattern

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.» onmousemove=»i18n(this)»>Параметр destructuredArrayIgnorePattern указывает исключения, использование которых не проверяется: элементы шаблонов деструктурирования массива, имена которых соответствуют шаблону регулярного выражения. Например, переменные, имена которых начинаются с подчеркивания.

caughtErrors

caughtErrors option is used for catch block arguments validation.» onmousemove=»i18n(this)»>Параметр caughtErrors используется для проверки аргументов блока catch .

У него две настройки:

  • none — do not check error objects. This is the default setting.» onmousemove=»i18n(this)»> none — не проверять ошибочные объекты. Это значение по умолчанию.
  • all — all named arguments must be used.» onmousemove=»i18n(this)»> all — должны использоваться все именованные аргументы.

caughtErrors: none

none .» onmousemove=»i18n(this)»>Отсутствие указания этого правила равносильно его none .

< «caughtErrors»: «none» >option:’ onmousemove=»i18n(this)»>Примеры правильного кода для параметра < «caughtErrors»: «none» >:

caughtErrors: all

< «caughtErrors»: «all» >option:’ onmousemove=»i18n(this)»>Примеры некорректного кода для параметра < «caughtErrors»: «all» >:

caughtErrorsIgnorePattern

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’.» onmousemove=»i18n(this)»>Параметр caughtErrorsIgnorePattern указывает исключения, использование которых не проверяется: перехватывайте аргументы, имена которых соответствуют шаблону регулярного выражения. Например, переменные, имена которых начинаются со строки «игнорировать».

Когда не использовать его

Если вы не хотите получать уведомления о неиспользуемых переменных или аргументах функций,вы можете смело отключить это правило.

Источник

no-unused-vars

Запретить неиспользуемые переменные

✅ Recommended

Свойство "extends": "eslint:recommended" в файле конфигурации включает это правило .

Переменные,которые объявлены и нигде не используются в коде,скорее всего,являются ошибкой из-за неполного рефакторинга.Такие переменные занимают место в коде и могут привести к путанице у читателей.

Rule Details

Данное правило направлено на устранение неиспользуемых переменных,функций и параметров функции.

Переменная foo считается использованной, если выполняется одно из следующих условий:

  • Он называется ( foo() ) или сконструирован ( new foo() )
  • Читается ( var bar = foo )
  • Он передается в функцию как аргумент ( doSomething(foo) )
  • Он читается внутри функции, которая передается другой функции ( doSomething(function() { foo(); }) )

Переменная не считается использованной, если она только когда-либо была объявлена ​​( var foo = 5 ) или присвоена ( foo = 7 ).

Примеры неправильного кода для этого правила:

Примеры правильного кода для этого правила:

/*eslint no-unused-vars: "error"*/var x = 10;alert(x);// foo is considered used heremyFunc(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;}

exported

В средах за пределами модулей CommonJS или ECMAScript вы можете использовать var для создания глобальной переменной, которая может использоваться другими скриптами. Вы можете использовать блок комментариев /* exported variableName */ чтобы указать, что эта переменная экспортируется и, следовательно, не должна считаться неиспользованной.

Обратите внимание, что /* exported */ не влияет ни на одно из следующего:

  • когда среда является node или commonjs
  • когда parserOptions.sourceType является module
  • когда ecmaFeatures.globalReturn является true

Комментарий к строке // exported variableName не будет работать, так как exported строка не зависит от конкретной строки.

Примеры правильного кода для операции /* exported variableName */ :

Options

Это правило принимает один аргумент, который может быть строкой или объектом. Настройки строки такие же, как у свойства vars (объяснено ниже).

По умолчанию это правило включено со all параметрами для переменных и after-used для аргументов.

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

vars

Опция vars имеет две настройки:

  • all проверяет все переменные на предмет использования, в том числе в глобальной области. Это значение по умолчанию.
  • local проверяет только то, что используются локально объявленные переменные, но допускает неиспользование глобальных переменных.

vars: local

Примеры правильного кода для параметра { "vars": "local" } :

/*eslint no-unused-vars: ["error", { "vars": "local" }]*//*global some_unused_var */some_unused_var = 42;

varsIgnorePattern

Параметр varsIgnorePattern указывает исключения, которые не следует проверять на использование: переменные, имена которых соответствуют шаблону регулярного выражения. Например, переменные, имена которых содержат ignored или Ignored .

Примеры правильного кода для параметра { "varsIgnorePattern": "[iI]gnored" } :

/*eslint no-unused-vars: ["error", { "varsIgnorePattern": "[iI]gnored" }]*/var firstVarIgnored = 1;var secondVar = 2;console.log(secondVar);

args

Параметр args имеет три настройки:

  • after-used — неиспользуемые позиционные аргументы, которые встречаются перед последним использованным аргументом, не будут проверяться, но будут проверены все именованные аргументы и все позиционные аргументы после последнего использованного аргумента.
  • all — должны использоваться все именованные аргументы.
  • none — не проверять аргументы.

args: after-used

Примеры неправильного кода для параметра по умолчанию { "args": "after-used" } :

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

/*eslint no-unused-vars: ["error", {"args": "after-used"}]*/(function(foo, bar, baz, qux) {    return qux;})();

args: all

Примеры неправильного кода для параметра { "args": "all" } :

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

/*eslint no-unused-vars: ["error", { "args": "none" }]*/(function(foo, bar, baz) {    return bar;})();

ignoreRestSiblings

Параметр ignoreRestSiblings является логическим (по умолчанию: false ). Используя Rest Property , можно «опустить» свойства объекта, но по умолчанию родственные свойства помечаются как «неиспользуемые». Если эта опция включена, соседние элементы остальных свойств игнорируются.

Примеры правильного кода для параметра { "ignoreRestSiblings": true } :

/*eslint no-unused-vars: ["error", { "ignoreRestSiblings": true }]*/// 'foo' and 'bar' were ignored because they have a rest property sibling.var { foo, ...coords } = data;var bar;({ bar, ...coords } = data);

argsIgnorePattern

Параметр argsIgnorePattern указывает исключения, которые не следует проверять на использование: аргументы, имена которых соответствуют шаблону регулярного выражения. Например, переменные, имена которых начинаются с подчеркивания.

Примеры правильного кода для параметра { "argsIgnorePattern": "^_" } :

/*eslint no-unused-vars: ["error", { "argsIgnorePattern": "^_" }]*/function foo(x, _y) {    return x + 1;}foo();

destructuredArrayIgnorePattern

Параметр destructuredArrayIgnorePattern указывает исключения, использование которых не проверяется: элементы шаблонов деструктурирования массива, имена которых соответствуют шаблону регулярного выражения. Например, переменные, имена которых начинаются с подчеркивания.

Примеры правильного кода для параметра { "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;

caughtErrors

Параметр caughtErrors используется для проверки аргументов блока catch .

У него две настройки:

  • none — не проверять ошибочные объекты. Это значение по умолчанию.
  • all — должны использоваться все именованные аргументы.

caughtErrors: none

Отсутствие указания этого правила равносильно его none .

Примеры правильного кода для параметра { "caughtErrors": "none" } :

/*eslint no-unused-vars: ["error", { "caughtErrors": "none" }]*/try {    //...} catch (err) {    console.error("errors");}

caughtErrors: all

Примеры некорректного кода для параметра { "caughtErrors": "all" } :

/*eslint no-unused-vars: ["error", { "caughtErrors": "all" }]*/// 1 error// "err" is defined but never usedtry {    //...} catch (err) {    console.error("errors");}

caughtErrorsIgnorePattern

Параметр caughtErrorsIgnorePattern указывает исключения, использование которых не проверяется: перехватывайте аргументы, имена которых соответствуют шаблону регулярного выражения. Например, переменные, имена которых начинаются со строки «игнорировать».

Примеры правильного кода для параметра { "caughtErrorsIgnorePattern": "^ignore" } :

/*eslint no-unused-vars: ["error", { "caughtErrorsIgnorePattern": "^ignore" }]*/try {    //...} catch (ignoreErr) {    console.error("errors");}

Когда не использовать его

Если вы не хотите получать уведомления о неиспользуемых переменных или аргументах функций,вы можете смело отключить это правило.

Version

Это правило было введено в ESLint v0.0.9.

Resources

  • Rule source
  • Tests source


ESLint

8.30

  • no-unused-labels

    Запретить неиспользуемые метки Свойство «extends»: «eslint:recommended» файл конфигурации включает это правило. Некоторые проблемы, о которых сообщает это правило, автоматически

  • no-unused-private-class-members

    Запретить неиспользуемые приватные члены класса Частные члены класса,которые объявлены и не используются нигде в коде,скорее всего,являются ошибкой из-за неполного рефакторинга.

  • no-use-before-define

    Запретить использование переменных до того,как они определены В JavaScript до ES6 объявления переменных и функций поднимаются на вершину области видимости,поэтому

  • no-useless-backreference

    Запретить бесполезные обратные ссылки в регулярных выражениях. Свойство «extends»: «eslint:recommended» файла конфигурации включает это правило. В JavaScript

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Error storage size of
  • Error statuslogger log4j2 could not find a logging implementation
  • Error startservicectrldispatcherw error ragent
  • Error starting workbench administrator
  • Error starting userland proxy

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии