Require or disallow semicolons in place of ASI (semi)

The –fix option on the command line automatically fixes some of the problems reported by this rule.

This rule enforces a consistent semicolon.

semi: ["error"."always"];
Copy the code
  • Rating: “error”
  • Option “always”: (default) requires semicolons at the end of statements
Examples of incorrect code for this rule with the default “always” option:
/*eslint semi: ["error", "always"]*/

var name = "ESLint";

object.method = function () {
  // ...
};
Copy the code
Examples of correct code for this rule with the default “always” option:
/*eslint semi: "error"*/

var name = "ESLint";

object.method = function () {
  // ...
};
Copy the code

Disallow unused variables (no-unused-vars)

This rule is designed to eliminate unused variables, methods, and parameter names in methods, and to warn when these are found. A variable is considered usable if it:

  • As a callback function
  • (var y = x)
  • Pass it in as an argument object (doSomething(x))
  • Is read in a function passed to another function

If a variable is only assigned (var x = 5) or declared, it is not considered for use.

'no-unused-vars': [
  'warn',
  {
    args: 'none'.ignoreRestSiblings: true,},]Copy the code
  • Rating: “warn”
  • Option “args”: None – Do not check arguments
  • The option “ignoreRestSiblings”: The option is a Boolean type (default: false). Using a Rest attribute may “omit” an attribute in an object, but by default its sibling attribute is marked as “unused”. Use this option to make the sibling properties of the REST property ignored.
Examples of correct code for this rule with the {“args”: “none”} option:
/*eslint no-unused-vars: ["error", { "args": "none" }]*/

(function (foo, bar, baz) {
  returnbar; }) ();Copy the code
Examples of correct code for this rule with the {“ignoreRestSiblings”: true} option:
/*eslint no-unused-vars: ["error", { "ignoreRestSiblings": true }]*/
// 'type' is ignored because it has a rest property sibling.
var{ type, ... coords } = data;Copy the code

Disable the console (no – the console)

This rule disallows calling methods on the console object.

'no-console': 'off'
Copy the code
  • Option “off”: disable

Enforces array method callbacks to have return statements (array-callback-return)

This rule finds the callback function for the following method and then checks the use of the return statement.

  • Array.from
  • Array.prototype.every
  • Array.prototype.filter
  • Array.prototype.find
  • Array.prototype.findIndex
  • Array.prototype.map
  • Array.prototype.reduce
  • Array.prototype.reduceRight
  • Array.prototype.some
  • Array.prototype.sort
  • The above types of data.
'array-callback-return': 'off'
Copy the code
  • Option “off”: disable

Require a Default branch in the Switch statement (default-case)

The purpose of this rule is to enforce the default branch in the switch statement. Alternatively, in the last case branch, use // no default to indicate that the default branch is not required. Comments can appear in any form, such as // No Default.

'default-case': ['warn', { commentPattern: '^no default$' }]
Copy the code
  • Rating: “warn”
  • Option “commentPattern “: Set the commentPattern to a regular expression string to change the default /^no default$/ I comment matching pattern. The purpose of this rule is to enforce the default branch in the switch statement. Alternatively, in the last case branch, use // no default to indicate that the default branch is not required. Comments can appear in any form, such as // No Default.
Examples of incorrect code for this rule:
/*eslint default-case: "error"*/

switch (a) {
  case 1:
    /* code */
    break;
}
Copy the code
Examples of correct code for this rule:
/*eslint default-case: "error"*/

switch (a) {
  case 1:
    /* code */
    break;

  default:
    /* code */
    break;
}

switch (a) {
  case 1:
    /* code */
    break;

  // no default
}

switch (a) {
  case 1:
    /* code */
    break;

  // No Default
}
Copy the code

Enforces line breaks before or after a dot (dot-location)

The –fix option on the command line automatically fixes some of the problems reported by this rule.

Rule syntax This rule is intended to enforce consistency in enforcing newlines in member expressions. Prevent the use of newline characters both before and after the dot operation.

'dot-location': ['warn'.'property']
Copy the code
  • Rating: “warn”
  • Option “property”: The dot operator in the expression should be on the same line as the property.
Examples of incorrect code for this rule with the “property” option:
/*eslint dot-location: ["error", "property"]*/
var foo = object.property;
Copy the code
Examples of correct code for this rule with the “property” option:
/*eslint dot-location: ["error", "property"]*/

var foo = object.property;
var bar = object.property;
Copy the code

Requires the use of === and! == (eqeqeq)

The –fix option on the command line automatically fixes some of the problems reported by this rule.

This rule is designed to eliminate non-type-safe equality operators.

eqeqeq: ["warn"."allow-null"];
Copy the code
  • Rating: “warn”
  • Option “allow-null”: Use “always” and then pass a “null” option with the property value” ignore “instead. This will tell ESLint to always force absolute equality except when comparing to null literals.

Requires parentheses when calling no-parameter constructors (new-parens)

The –fix option on the command line automatically fixes some of the problems reported by this rule.

This rule is intended to improve code clarity by requiring parentheses when calling constructors with the new keyword.

'new-parens': 'warn'
Copy the code
  • Rating: “warn”
Examples of incorrect code for this rule:
/*eslint new-parens: "error"*/

var person = new Person();
var person = new Person();
Copy the code
Examples of correct code for this rule:
/*eslint new-parens: "error"*/

var person = new Person();
var person = new Person();
Copy the code

Disallow Array constructors (no-array-constructor)

This rule disallows the use of Array constructors.

'no-array-constructor': 'warn'
Copy the code
  • Rating: “warn”
Examples of incorrect code for this rule:
/*eslint no-array-constructor: "error"*/

Array(0.1.2);
/*eslint no-array-constructor: "error"*/

new Array(0.1.2);
Copy the code
Examples of correct code for this rule:
/*eslint no-array-constructor: "error"*/

Array(500);
/*eslint no-array-constructor: "error"*/

new Array(someOtherArray.length);
Copy the code

Disable caller or callee (no-caller)

This rule is designed to prevent deprecated and suboptimal code from being used, and to disallow arguments.caller and arguments.callee. Therefore, this rule will warn when arguments.caller and arguments.callee are used.

'no-caller': 'warn'
Copy the code
  • Rating: “warn”
Error Code examples
/*eslint no-caller: "error"*/

function foo(n) {
  if (n <= 0) {
    return;
  }

  arguments.callee(n - 1);
}

[1.2.3.4.5].map(function (n) {
  return! (n >1)?1 : arguments.callee(n - 1) * n;
});
Copy the code
Examples of correct code for this rule:
/*eslint no-caller: "error"*/

function foo(n) {
  if (n <= 0) {
    return;
  }

  foo(n - 1);
}

[1.2.3.4.5].map(function factorial(n) {
  return! (n >1)?1 : factorial(n - 1) * n;
});
Copy the code

Disallow the assignment operator in conditional statements (no-cond-assign)

This rule disallows if, for, while and do… An ambiguous assignment operator in a while statement.

'no-cond-assign': ['warn'.'always']
Copy the code
  • Rating: “warn”
  • The “always” option disallows assignment statements in conditional statements.
Examples of incorrect code for this rule with the “always” option:
/*eslint no-cond-assign: ["error", "always"]*/

// Unintentional assignment
var x;
if ((x = 0)) {
  var b = 1;
}

// Practical example that is similar to an error
function setHeight(someNode) {
  "use strict";
  do {
    someNode.height = "100px";
  } while ((someNode = someNode.parentNode));
}

// Practical example that wraps the assignment in parentheses
function setHeight(someNode) {
  "use strict";
  do {
    someNode.height = "100px";
  } while ((someNode = someNode.parentNode));
}

// Practical example that wraps the assignment and tests for 'null'
function setHeight(someNode) {
  "use strict";
  do {
    someNode.height = "100px";
  } while((someNode = someNode.parentNode) ! = =null);
}
Copy the code
Examples of correct code for this rule with the “always” option:
/*eslint no-cond-assign: ["error", "always"]*/

// Assignment replaced by comparison
var x;
if (x === 0) {
  var b = 1;
}
Copy the code

Do not change variables declared as const (no-const-assign)

This rule is designed to mark changes to variables declared with the const keyword.

'no-const-assign': 'warn'
Copy the code
  • Rating: “warn”
Examples of incorrect code for this rule:
/*eslint no-const-assign: "error"*/
/*eslint-env es6*/

const a = 0;
a = 1;
/*eslint no-const-assign: "error"*/
/*eslint-env es6*/

const a = 0;
a += 1;
/*eslint no-const-assign: "error"*/
/*eslint-env es6*/

const a = 0;
++a;
Copy the code
Examples of correct code for this rule:
/*eslint no-const-assign: "error"*/
/*eslint-env es6*/

const a = 0;
console.log(a);
/*eslint no-const-assign: "error"*/
/*eslint-env es6*/

for (const a in [1.2.3]) {
  // `a` is re-defined (not modified) on each loop step.
  console.log(a);
}
/*eslint no-const-assign: "error"*/
/*eslint-env es6*/

for (const a of [1.2.3]) {
  // `a` is re-defined (not modified) on each loop step.
  console.log(a);
}
Copy the code

Disallow control characters in regular expressions (no-control-regex)

Rule Description This rule disallows control characters in regular expressions.

'no-control-regex': 'warn'
Copy the code
  • Rating: “warn”
Examples of incorrect code for this rule:
/*eslint no-control-regex: "error"*/

var pattern1 = /\x1f/;
var pattern2 = new RegExp("\x1f");
Copy the code
Examples of correct code for this rule:
/*eslint no-control-regex: "error"*/

var pattern1 = /\x20/;
var pattern2 = new RegExp("\x20");
Copy the code

Disallow variable deletion (no-delete-var)

This rule disallows the use of the delete operator on variables.

If ESLint parses code in strict mode, the parser (not this rule) will report an error.

'no-delete-var': 'warn'
Copy the code
  • Rating: “warn”
Examples of incorrect code for this rule:
/*eslint no-delete-var: "error"*/

var x;
delete x;
Copy the code

Disallow duplicate arguments in function definitions (no-dupe-args)

Rule Description This rule disallows the use of named parameters in function definitions or expressions. This rule does not apply to arrow functions or class methods, because the parser will report such an error.

If ESLint parses code in strict mode, the parser (not this rule) will report such an error.

'no-dupe-args': 'warn'
Copy the code
  • Rating: “warn”
Examples of incorrect code for this rule:
/*eslint no-dupe-args: "error"*/

function foo(a, b, a) {
  console.log("value of the second a:", a);
}

var bar = function (a, b, a) {
  console.log("value of the second a:", a);
};
Copy the code
Examples of correct code for this rule:
/*eslint no-dupe-args: "error"*/

function foo(a, b, c) {
  console.log(a, b, c);
}

var bar = function (a, b, c) {
  console.log(a, b, c);
};
Copy the code

Do not allow duplicate names in class members (no-dupe-class-members)

This rule is designed to flag the use of duplicate names in class members.

'no-dupe-class-members': 'warn'
Copy the code
  • Rating: “warn”
Examples of incorrect code for this rule:
/*eslint no-dupe-class-members: "error"*/
/*eslint-env es6*/

class Foo {
  bar() {}
  bar() {}
}

class Foo {
  bar() {}
  get bar() {}
}

class Foo {
  static bar() {}
  static bar() {}
}
Copy the code
Examples of correct code for this rule:
/*eslint no-dupe-class-members: "error"*/
/*eslint-env es6*/

class Foo {
  bar() {}
  qux() {}
}

class Foo {
  get bar() {}
  set bar(value) {}
}

class Foo {
  static bar() {}
  bar() {}
}
Copy the code

Disallow duplicate keys in object literals (no-dupe-keys)

This rule disallows duplicate keys in object literals.

'no-dupe-keys': 'warn'
Copy the code
  • Rating: “warn”
Examples of incorrect code for this rule:
/*eslint no-dupe-keys: "error"*/

var foo = {
  bar: "baz".bar: "qux"};var foo = {
  bar: "baz".bar: "qux"};var foo = {
  0x1: "baz".1: "qux"};Copy the code
Examples of correct code for this rule:
/*eslint no-dupe-keys: "error"*/

var foo = {
  bar: "baz".quxx: "qux"};Copy the code

Disallow duplicate case labels (no-duplicate-case)

This rule disallows duplicate test expressions in case clauses of a switch statement.

'no-duplicate-case': 'warn'
Copy the code
  • Rating: “warn”
Examples of incorrect code for this rule:
/*eslint no-duplicate-case: "error"*/

var a = 1,
  one = 1;

switch (a) {
  case 1:
    break;
  case 2:
    break;
  case 1: // duplicate test expression
    break;
  default:
    break;
}

switch (a) {
  case one:
    break;
  case 2:
    break;
  case one: // duplicate test expression
    break;
  default:
    break;
}

switch (a) {
  case "1":
    break;
  case "2":
    break;
  case "1": // duplicate test expression
    break;
  default:
    break;
}
Copy the code
Examples of correct code for this rule:
/*eslint no-duplicate-case: "error"*/

var a = 1,
  one = 1;

switch (a) {
  case 1:
    break;
  case 2:
    break;
  case 3:
    break;
  default:
    break;
}

switch (a) {
  case one:
    break;
  case 2:
    break;
  case 3:
    break;
  default:
    break;
}

switch (a) {
  case "1":
    break;
  case "2":
    break;
  case "3":
    break;
  default:
    break;
}
Copy the code

Disallow empty character sets in regular expressions (no-empty-character-class)

Rule Description This rule disallows empty character sets in regular expressions.

'no-empty-character-class': 'warn'
Copy the code
  • Rating: “warn”
Examples of incorrect code for this rule:
/*eslint no-empty-character-class: "error"*/

/^abc[]/.test("abcdefg"); // false
"abcdefg".match(/^abc[]/); // null
Copy the code
Examples of correct code for this rule:
/*eslint no-empty-character-class: "error"*/

/^abc/.test("abcdefg"); // true
"abcdefg".match(/^abc/); // ["abc"]

/^abc[a-z]/.test("abcdefg"); // true
"abcdefg".match(/^abc[a-z]/); // ["abcd"]
Copy the code

Disallow empty destructuring patterns (no-empty-pattern)

The purpose of this rule is to flag any empty patterns in destructed objects and arrays and report a problem whenever one is encountered.

'no-empty-pattern': 'warn'
Copy the code
  • Rating: “warn”
Examples of incorrect code for this rule:
/*eslint no-empty-pattern: "error"*/

var {} = foo;
var [] = foo;
var {
  a: {},
} = foo;
var {
  a: [],
} = foo;
function foo({}) {}
function foo([]) {}
function foo({ a: {} }) {}
function foo({ a: [] }) {}
Copy the code
Examples of correct code for this rule:
/*eslint no-empty-pattern: "error"*/

var { a = {} } = foo;
var { a = [] } = foo;
function foo({ a = {} }) {}
function foo({ a = [] }) {}
Copy the code

Disable eval() (no-eval)

This rule is designed to avoid potentially dangerous, unnecessary, and inefficient code by disallowing the use of the eval() function. Therefore, this rule will issue a warning when the eval() function is used.

'no-eval': 'warn'
Copy the code
  • Rating: “warn”
Examples of incorrect code for this rule:
/*eslint no-eval: "error"*/

var obj = { x: "foo" },
  key = "x",
  value = eval("obj." + key);

(0.eval) ("var a = 0");

var foo = eval;
foo("var a = 0");

// This `this` is the global object.
this.eval("var a = 0");
Copy the code
Examples of correct code for this rule:
/*eslint no-eval: "error"*/
/*eslint-env es6*/

var obj = { x: "foo" },
  key = "x",
  value = obj[key];

class A {
  foo() {
    // This is a user-defined method.
    this.eval("var a = 0");
  }

  eval() {}}Copy the code

Disallow reassignment of exceptions in catch clauses (no-ex-assign)

Rule description This rule disallows reassigning an exception in a catch clause.

'no-ex-assign': 'warn'
Copy the code
  • Rating: “warn”
Examples of incorrect code for this rule:
/*eslint no-ex-assign: "error"*/

try {
  // code
} catch (e) {
  e = 10;
}
Copy the code
Examples of correct code for this rule:
/*eslint no-ex-assign: "error"*/

try {
  // code
} catch (e) {
  var foo = 10;
}
Copy the code

Disallow extending native objects (no-extend-native)

Do not directly modify the properties of built-in objects.

'no-extend-native': 'warn'
Copy the code
  • Rating: “warn”
Examples of incorrect code for this rule:
/*eslint no-extend-native: "error"*/

Object.prototype.a = "a";
Object.defineProperty(Array.prototype, "times", { value: 999 });
Copy the code

Disallow unnecessary function binding (no-extra-bind)

The –fix option on the command line automatically fixes some of the problems reported by this rule.

This rule is intended to avoid unnecessary use of bind() and will warn if an immediate function expression (IIFE) uses bind() but does not have an appropriate this value. This rule does not flag the use of bind() with function arguments bound.

Note: Arrow functions cannot set their own this value by using bind(). This rule marks all arrow functions that use bind() as problematic.

'no-extra-bind': 'warn'
Copy the code
  • Rating: “warn”
Examples of incorrect code for this rule:
/*eslint no-extra-bind: "error"*/
/*eslint-env es6*/

var x = function () {
  foo();
}.bind(bar);

var x = (() = > {
  foo();
}).bind(bar);

var x = (() = > {
  this.foo();
}).bind(bar);

var x = function () {(function () {
    this.foo(); }) (); }.bind(bar);var x = function () {
  function foo() {
    this.bar();
  }
}.bind(baz);
Copy the code
Examples of correct code for this rule:
/*eslint no-extra-bind: "error"*/

var x = function () {
  this.foo();
}.bind(bar);

var x = function (a) {
  return a + 1;
}.bind(foo, bar);
Copy the code

Disabling unnecessary labels (no-extra-label)

The –fix option on the command line automatically fixes some of the problems reported by this rule.

This rule is designed to eliminate unnecessary labels.

'no-extra-label': 'warn'
Copy the code
  • Rating: “warn”
Examples of incorrect code for this rule:
/*eslint no-extra-label: "error"*/

A: while (a) {
  break A;
}

B: for (let i = 0; i < 10; ++i) {
  break B;
}

C: switch (a) {
  case 0:
    break C;
}
Copy the code
Examples of correct code for this rule:
/*eslint no-extra-label: "error"*/

while (a) {
  break;
}

for (let i = 0; i < 10; ++i) {
  break;
}

switch (a) {
  case 0:
    break;
}

A: {
  break A;
}

B: while (a) {
  while (b) {
    break B;
  }
}

C: switch (a) {
  case 0:
    while (b) {
      break C;
    }
    break;
}
Copy the code

Disallow case statements to fallthrough (no-fallthrough)

The rule aims to eliminate unintended case failures. As a result, it will mark failures that are not marked with comments.

'no-fallthrough': 'warn'
Copy the code
  • Rating: “warn”
Examples of incorrect code for this rule:
/*eslint no-fallthrough: "error"*/

switch (foo) {
  case 1:
    doSomething();

  case 2:
    doSomething();
}
Copy the code
Examples of correct code for this rule:
/*eslint no-fallthrough: "error"*/

switch (foo) {
  case 1:
    doSomething();
    break;

  case 2:
    doSomething();
}

function bar(foo) {
  switch (foo) {
    case 1:
      doSomething();
      return;

    case 2: doSomething(); }}switch (foo) {
  case 1:
    doSomething();
    throw new Error("Boo!");

  case 2:
    doSomething();
}

switch (foo) {
  case 1:
  case 2:
    doSomething();
}

switch (foo) {
  case 1:
    doSomething();
  // falls through

  case 2:
    doSomething();
}
Copy the code

Disallow reassigning function declarations (no-fuc-assign)

This rule disallows reassigning a function declaration.

'no-func-assign': 'warn'
Copy the code
  • Rating: “warn”
Examples of incorrect code for this rule:
/*eslint no-func-assign: "error"*/

function foo() {}
foo = bar;

function foo() {
  foo = bar;
}
Copy the code
Examples of correct code for this rule:
/*eslint no-func-assign: "error"*/

var foo = function () {};
foo = bar;

function foo(foo) {
  // `foo` is shadowed.
  foo = bar;
}

function foo() {
  var foo = bar; // `foo` is shadowed.
}
Copy the code

Disallow implied eval() (no-implied-eval)

This rule is intended to eliminate implicit eval() when using setTimeout(), setInterval(), or execScript(). Therefore, this rule will warn when either of them uses a string as the first argument.

'no-implied-eval': 'warn'
Copy the code
  • Rating: “warn”
Examples of incorrect code for this rule:
/*eslint no-implied-eval: "error"*/

setTimeout("alert('Hi! ');".100);

setInterval("alert('Hi! ');".100);

execScript("alert('Hi! ')");

window.setTimeout("count = 5".10);

window.setInterval("foo = bar".10);
Copy the code
Examples of correct code for this rule:
/*eslint no-implied-eval: "error"*/

setTimeout(function () {
  alert("Hi!");
}, 100);

setInterval(function () {
  alert("Hi!");
}, 100);
Copy the code

Disallow invalid regular expressions in RegExp constructors (no-invalid-regexp)

This rule disallows invalid regular expressions in RegExp constructors.

'no-invalid-regexp': 'warn'
Copy the code
  • Rating: “warn”
Examples of incorrect code for this rule:
/*eslint no-invalid-regexp: "error"*/

RegExp("[");

RegExp("."."z");

new RegExp("\ \");
Copy the code
Examples of correct code for this rule:
/*eslint no-invalid-regexp: "error"*/

RegExp(".");

new RegExp(a);this.RegExp("[");
Copy the code

Disable iterator (no-iterator)

This rule is designed to prevent errors due to the use of the iterator property, which is not implemented by all browsers. Therefore, this rule will warn when iterator properties are encountered.

'no-iterator': 'warn'
Copy the code
  • Rating: “warn”
Examples of incorrect code for this rule:
/*eslint no-iterator: "error"*/

Foo.prototype.__iterator__ = function () {
  return new FooIterator(this);
};

foo.__iterator__ = function () {};

foo["__iterator__"] = function () {};
Copy the code
Examples of correct code for this rule:
/*eslint no-iterator: "error"*/

var __iterator__ = foo; // Not using the `__iterator__` property.
Copy the code

Disable labels with the same name as variables (no-label-var)

This rule is designed to create clearer code by disallowing the use of variables of the same name in the same scope as tags.

'no-label-var': 'warn'
Copy the code
  • Rating: “warn”
Examples of incorrect code for this rule:
/*eslint no-label-var: "error"*/

var x = foo;
function bar() {
  x: for (;;) {
    breakx; }}Copy the code
Examples of correct code for this rule:
/*eslint no-label-var: "error"*/

// The variable that has the same name as the label is not in scope.

function foo() {
  var q = t;
}

function bar() {
  q: for (;;) {
    breakq; }}Copy the code

Disallow label statements (no-labels)

This rule is designed to eliminate the use of tags in JavaScript. This rule will issue a warning when a label statement is encountered.

'no-labels': ['warn', { allowLoop: true.allowSwitch: false }]
Copy the code
  • Rating: “warn”
  • Option “allowLoop”: (Boolean, default is false) – If this option is set to true, this rule ignores labels in loop statements.
Examples of correct code for this rule with the {“allowLoop”: true} option:
/*eslint no-labels: ["error", { "allowLoop": true }]*/

label: while (true) {
  break label;
}
Copy the code

Disable unnecessary nested blocks (no-lone-blocks)

This rule is designed to eliminate unnecessary and potentially confusing code blocks at the top of the script or in other blocks.

'no-lone-blocks': 'warn'
Copy the code
  • Rating: “warn”
Examples of incorrect code for this rule:
/*eslint no-lone-blocks: "error"*/{}if(foo) { bar(); { baz(); }}function bar() { { baz(); }} {function foo() {{}}aLabel: {}}Copy the code
Examples of correct code for this rule:
/*eslint no-lone-blocks: "error"*/
/*eslint-env es6*/

while (foo) {
  bar();
}

if (foo) {
  if(bar) { baz(); }}function bar() {
  baz();
}

{
  let x = 1;
}

{
  const y = 1;
}

{
  class Foo {}
}

aLabel: {
}
Copy the code

Disallow functions in loops (no-loop-func)

This error causes your code to not work as you expect it to, and it also indicates a misunderstanding of JavaScript. If you don’t fix this bug, your code may work fine, but in some cases, it may behave in an unexpected way.

'no-loop-func': 'warn'
Copy the code
  • Rating: “warn”
Examples of incorrect code for this rule:
/*eslint no-loop-func: "error"*/
/*eslint-env es6*/

for (var i = 10; i; i--) {
  (function () {
    returni; }) (); }while (i) {
  var a = function () {
    return i;
  };
  a();
}

do {
  function a() {
    return i;
  }
  a();
} while (i);

let foo = 0;
for (let i = 10; i; i--) {
  // Bad, function is referencing block scoped variable in the outer scope.
  var a = function () {
    return foo;
  };
  a();
}
Copy the code
Examples of correct code for this rule:
/*eslint no-loop-func: "error"*/
/*eslint-env es6*/

var a = function () {};

for (var i = 10; i; i--) {
  a();
}

for (var i = 10; i; i--) {
  var a = function () {}; // OK, no references to variables in the outer scopes.
  a();
}

for (let i = 10; i; i--) {
  var a = function () {
    return i;
  }; // OK, all references are referring to block scoped variables in the loop.
  a();
}

var foo = 100;
for (let i = 10; i; i--) {
  var a = function () {
    return foo;
  }; // OK, all references are referring to never modified variables.
  a();
}
/ /... no modifications of foo after this loop ...
Copy the code

Disallow mixing different operators (no-mixed-operators)

This rule checks BinaryExpression and LogicalExpression. This rule may be related to the no-extra-Parens rule. If you use both this rule and the no-extra-Parens rule, you need to use the nestedBinaryExpressions option of the no-extra-Parens rule.

'no-mixed-operators': [
      'warn',
      {
        groups: [['&'.'|'.A '^'.'~'.'< <'.'> >'.'> > >'],
          ['= ='.'! = '.'= = ='.'! = = '.'>'.'> ='.'<'.'< ='],
          ['&'.'| |'],
          ['in'.'instanceof']],allowSamePrecedence: false,},]Copy the code
  • Rating: “warn”
  • Option “Groups “: (string[][]) – Specifies which operator groups to compare. When comparing two operators, the rule checks if the operators are in the same group. Otherwise this rule ignores it. Its value is a list group. This group is a list of binary operators. The default is a group of various operators.
  • Option “allowSamePrecedence “: (Boolean) – Specifies that two mixed operators are allowed, provided they have the same precedence. The default is true.
Options {” groups “: [[” &”, “|”, “^”, “-“, “< <“, “> >”, “> > >”], [” & “, “| |”]]} the error code sample:
/*eslint no-mixed-operators: ["error", {"groups": [["&", "|", "^", "~", "<<", ">>", ">>>"], ["&&", "||"]]}]*/

var foo = (a && b < 0) || c > 0 || d + 1= = =0;
var foo = (a & b) | c;
Copy the code
Options {” groups “: [[” &”, “|”, “^”, “-“, “< <“, “> >”, “> > >”], [” & “, “| |”]]} the correct code sample:
/*eslint no-mixed-operators: ["error", {"groups": [["&", "|", "^", "~", "<<", ">>", ">>>"], ["&&", "||"]]}]*/

var foo = a || b > 0 || c + 1= = =0;
var foo = a && b > 0 && c + 1= = =0;
var foo = (a && b < 0) || c > 0 || d + 1= = =0;
var foo = a && (b < 0 || c > 0 || d + 1= = =0);
var foo = (a & b) | c;
var foo = a & (b | c);
var foo = a + b * c;
var foo = a + b * c;
var foo = (a + b) * c;
Copy the code
Examples of incorrect code for this rule with the {“allowSamePrecedence”: false} option:
/*eslint no-mixed-operators: ["error", {"allowSamePrecedence": false}]*/

// + and - have the same precedence.
var foo = a + b - c;
Copy the code

Disallow multi-line strings (no-multi-str)

This rule is designed to prevent the use of multi-line strings.

'no-multi-str': 'warn'
Copy the code
  • Rating: “warn”
Examples of incorrect code for this rule:
/*eslint no-multi-str: "error"*/
var x =
  "Line 1 \ Line 2";
Copy the code
Examples of correct code for this rule:
/*eslint no-multi-str: "error"*/

var x = "Line 1\n" + "Line 2";
Copy the code

Disallow redistribution of local objects (no-native-resssign)

Version This rule was deprecated in ESLint V3.3.0 and replaced by the no-global-assign rule.

This rule does not allow modification of read-only global variables. ESLint can configure global variables to be read-only.

  • Specify the environment
  • The specified global
'no-native-reassign': 'warn'
Copy the code
  • Rating: “warn”
Examples of incorrect code for this rule:
/*eslint no-native-reassign: "error"*/

Object = null;
undefined = 1;
/*eslint no-native-reassign: "error"*/
/*eslint-env browser*/

window = {};
length = 1;
top = 1;
/*eslint no-native-reassign: "error"*/
/*globals a:false*/

a = 1;
Copy the code
Examples of correct code for this rule:
/*eslint no-native-reassign: "error"*/

a = 1;
var b = 1;
b = 2;
/*eslint no-native-reassign: "error"*/
/*eslint-env browser*/

onload = function () {};
/*eslint no-native-reassign: "error"*/
/*globals a:true*/

a = 1;
Copy the code

Do not negate the left operand in in expressions (no-negated-in-lhs)

This rule was deprecated in ESLint V3.3.0 and replaced with no-unsafe-negation.

This rule does not allow negation of the left operand in an in expression.

'no-negated-in-lhs': 'warn'
Copy the code
  • Rating: “warn”
Examples of incorrect code for this rule:
/*eslint no-negated-in-lhs: "error"*/

if(! keyin object) {
  // operator precedence makes it equivalent to (! key) in object
  // and type conversion makes it equivalent to (key ? "false" : "true") in object
}
Copy the code
Examples of correct code for this rule:
/*eslint no-negated-in-lhs: "error"*/

if(! (keyin object)) {
  // key is not in object
}

if ("" + !key in object) {
  // make operator precedence and type conversion explicit
  // in a rare situation when that is the intended meaning
}
Copy the code

Disable Function constructor (no-new-func)

This rule highlights the use of bad practices. To pass a string to the Function constructor, you need the engine to parse the string, just as if you were calling eval.

'no-new-func': 'warn'
Copy the code
  • Rating: “warn”
Examples of incorrect code for this rule:
/*eslint no-new-func: "error"*/

var x = new Function("a"."b"."return a + b");
var x = Function("a"."b"."return a + b");
Copy the code
Examples of correct code for this rule:
/*eslint no-new-func: "error"*/

var x = function (a, b) {
  return a + b;
};
Copy the code

Disallow the Object constructor (no-new-object)

This rule disallows the use of Object constructors.

'no-new-object': 'warn'
Copy the code
  • Rating: “warn”
Examples of incorrect code for this rule:
/*eslint no-new-object: "error"*/

var myObject = new Object(a);var myObject = new Object(a);Copy the code
Examples of correct code for this rule:
/*eslint no-new-object: "error"*/

var myObject = new CustomObject();

var myObject = {};
Copy the code

Disallow the use of the Symbol constructor (no-new-symbol)

This rule is used to prevent unexpected calls to Symbol and new operators.

'no-new-symbol': 'warn'
Copy the code
  • Rating: “warn”
Examples of incorrect code for this rule:
/*eslint no-new-symbol: "error"*/
/*eslint-env es6*/

var foo = new Symbol("foo");
Copy the code
Examples of correct code for this rule:
/*eslint no-new-symbol: "error"*/
/*eslint-env es6*/

var foo = Symbol("foo");

// Ignores shadowed Symbol.
function bar(Symbol) {
  const baz = new Symbol("baz");
}
Copy the code

Disallow raw wrapper instances (no-new-wrappers)

This rule is intended to eliminate the use of String, Number, and Boolean through the new operator. Therefore, this rule warns whenever a new String, new Number, or new Boolean is encountered.

'no-new-wrappers': 'warn'
Copy the code
  • Rating: “warn”
Examples of incorrect code for this rule:
/*eslint no-new-wrappers: "error"*/

var stringObject = new String("Hello world");
var numberObject = new Number(33);
var booleanObject = new Boolean(false);

var stringObject = new String(a);var numberObject = new Number(a);var booleanObject = new Boolean(a);Copy the code
Examples of correct code for this rule:
/*eslint no-new-wrappers: "error"*/

var text = String(someValue);
var num = Number(someValue);

var object = new MyString();
Copy the code

Disallow calling global objects as functions (no-obj-calls)

This rule disallows calling Math, JSON, and Reflect objects as functions.

'no-obj-calls': 'warn'
Copy the code
  • Rating: “warn”
Examples of incorrect code for this rule:
/*eslint no-obj-calls: "error"*/

var math = Math(a);var json = JSON(a);var reflect = Reflect(a);Copy the code
Examples of correct code for this rule:
/*eslint no-obj-calls: "error"*/

function area(r) {
  return Math.PI * r * r;
}
var object = JSON.parse("{}");
var value = Reflect.get({ x: 1.y: 2 }, "x");
Copy the code

Disabling octal literals (no-octal)

'no-octal': 'warn'
Copy the code
  • Rating: “warn”
Examples of incorrect code for this rule:
/*eslint no-octal: "error"*/

var num = 071;
var result = 5 + 07;
Copy the code
Examples of correct code for this rule:
/*eslint no-octal: "error"*/

var num = "071";
Copy the code

Disallow octal escape sequences in string literals (no-octal-escape)

This rule disallows the use of octal escape sequences in string literals. If ESLint parses code in strict mode, the parser (not this rule) will report an error.

'no-octal-escape': 'warn'
Copy the code
  • Rating: “warn”
Examples of incorrect code for this rule:
/*eslint no-octal-escape: "error"*/

var foo = "Copyright \251";
Copy the code
Examples of correct code for this rule:
/*eslint no-octal-escape: "error"*/

var foo = "Copyright \u00A9"; // unicode

var foo = "Copyright \xA9"; // hexadecimal
Copy the code

Disallow redeclare variables (no-redeclare)

This rule is designed to eliminate multiple declarations of the same variable in the same scope.

'no-redeclare': 'warn'
Copy the code
  • Rating: “warn”
Examples of incorrect code for this rule:
/*eslint no-redeclare: "error"*/

var a = 3;
var a = 10;
Copy the code
Examples of correct code for this rule:
/*eslint no-redeclare: "error"*/

var a = 3;
// ...
a = 10;
Copy the code

Disallow multiple Spaces in regular expression literals (no-regex-spaces)

This rule disallows multiple Spaces in regular expression literals.

'no-regex-spaces': 'warn'
Copy the code
  • Rating: “warn”
Examples of incorrect code for this rule:
/*eslint no-regex-spaces: "error"*/

var re = /foo bar/;
var re = new RegExp("foo bar");
Copy the code
Examples of correct code for this rule:
/*eslint no-regex-spaces: "error"*/

var re = /foo {3}bar/;
var re = new RegExp("foo {3}bar");
Copy the code

(no-restricted-syntax)

This rule disallows the use of specific (user-specified) syntax.

'no-restricted-syntax': ['warn'.'WithStatement']
Copy the code
  • Rating: “warn”
  • Option “WithStatement”: disables with
Examples of incorrect code for this rule in the options dialog “FunctionExpression”, “WithStatement”, BinaryExpression[operator=’in’] :
/* eslint no-restricted-syntax: ["error", "FunctionExpression", "WithStatement", "BinaryExpression[operator='in']"] */

with (me) {
  dontMess();
}

var doSomething = function () {};

foo in bar;
Copy the code
Examples of correct code for this rule in the options dialog “FunctionExpression”, “WithStatement” :
/* eslint no-restricted-syntax: ["error", "FunctionExpression", "WithStatement", "BinaryExpression[operator='in']"] */

me.dontMess();

function doSomething() {}

foo instanceof bar;
Copy the code

Disabling Script URLS (no-script-URL)

'no-script-url': 'warn'
Copy the code
  • Rating: “warn”
Examples of incorrect code for this rule:
/*eslint no-script-url: "error"*/

location.href = "javascript:void(0)";
Copy the code

Disallow self-assign (no-self-assign)

This rule is designed to eliminate self-assignment.

'no-self-assign': 'warn'
Copy the code
  • Rating: “warn”
Examples of incorrect code for this rule:
/*eslint no-self-assign: "error"*/

foo = foo;

[a, b] = [a, b];

[a, ...b] = [x, ...b];

({ a, b } = { a, x });
Copy the code
Examples of correct code for this rule:
/*eslint no-self-assign: "error"*/

foo = bar;
[a, b] = [b, a];

// This pattern is warned by the `no-use-before-define` rule.
let foo = foo;

// The default values have an effect.
[foo = 1] = [foo];
Copy the code

Disallow self-compare

This rule is used to highlight potentially confusing, meaningless code. There are few scenarios where you need to compare the variables themselves.

'no-self-compare': 'warn'
Copy the code
  • Rating: “warn”
Examples of incorrect code for this rule:
/*eslint no-self-compare: "error"*/

var x = 10;
if (x === x) {
  x = 20;
}
Copy the code

Comma operators are not allowed (no-sequences)

This rule disallows the use of the comma operator except in the following cases:

  • When initializing or updating part of the for statement.
  • If the expression sequence is explicitly wrapped in parentheses.
'no-sequences': 'warn'
Copy the code
  • Rating: “warn”
Examples of incorrect code for this rule:
/*eslint no-sequences: "error"*/

(foo = doSomething()), val;

0.eval("doSomething();");

do {} while((doSomething(), !! test));for(; doSomething(), !! test; ) ;if((doSomething(), !! test));switch (((val = foo()), val)) {
}

while (((val = foo()), val < 42));

with ((doSomething(), val)) {
}
Copy the code
Examples of correct code for this rule:
/*eslint no-sequences: "error"*/

foo = (doSomething(), val);

(0.eval) ("doSomething();");

do {} while((doSomething(), !! test));for (i = 0, j = 10; i < j; i++, j--);

if((doSomething(), !! test));switch (((val = foo()), val)) {
}

while (((val = foo()), val < 42));

// with ((doSomething(), val)) {}
Copy the code

Keywords cannot be Shadowed (no-shadow-restricted-names)

'no-shadow-restricted-names': 'warn'
Copy the code
  • Rating: “warn”
Examples of incorrect code for this rule:
/*eslint no-shadow-restricted-names: "error"*/

function NaN() {}!function (Infinity) {};

var undefined;

try{}catch (eval) {}
Copy the code
Examples of correct code for this rule:
/*eslint no-shadow-restricted-names: "error"*/

var Object;

function f(a, b) {}
Copy the code

Disable sparse arrays (no-sparse arrays)

This rule disallows the use of sparse arrays, that is, arrays that have no elements preceded by commas. This rule does not apply to trailing commas that follow the last element.

'no-sparse-arrays': 'warn'
Copy the code
  • Rating: “warn”
Examples of incorrect code for this rule:
/*eslint no-sparse-arrays: "error"*/

var items = [,];
var colors = ["red"."blue"];
Copy the code
Examples of correct code for this rule:
/*eslint no-sparse-arrays: "error"*/

var items = [];
var items = new Array(23);

// trailing comma (after the last element) is not a problem
var colors = ["red"."blue"];
Copy the code

Template literal placeholder syntax is not allowed in regular strings (no-template-curled-in-string)

The purpose of this rule is to warn when a regular string contains a placeholder on a template literal. It will find the positional character ({something}), which uses “or” quotation marks.

'no-template-curly-in-string': 'warn'
Copy the code
  • Rating: “warn”
Examples of incorrect code for this rule:
/*eslint no-template-curly-in-string: "error"*/
"Hello ${name}!";
"Hello ${name}!";
"Time: ${12 * 60 * 60 * 1000}";
Copy the code
Examples of correct code for this rule:
/*eslint no-template-curly-in-string: "error"*/
`Hello ${name}! `;
`Time: The ${12 * 60 * 60 * 1000}`;

templateFunction`Hello ${name}`;
Copy the code

Disallow the use of this or super before calling super() in the constructor. (no-this-before-super)

This rule is designed to flag situations where this or super is used before calling super().

'no-this-before-super': 'warn'
Copy the code
  • Rating: “warn”
Examples of incorrect code for this rule:
/*eslint no-this-before-super: "error"*/
/*eslint-env es6*/

class A extends B {
  constructor() {
    this.a = 0;
    super();
  }
}

class A extends B {
  constructor() {
    this.foo();
    super();
  }
}

class A extends B {
  constructor() {
    super.foo();
    super();
  }
}

class A extends B {
  constructor() {
    super(this.foo()); }}Copy the code
Examples of correct code for this rule:
/*eslint no-this-before-super: "error"*/
/*eslint-env es6*/

class A {
  constructor() {
    this.a = 0; // OK, this class doesn't have an `extends` clause.}}class A extends B {
  constructor() {
    super(a);this.a = 0; // OK, this is after `super()`.}}class A extends B {
  foo() {
    this.a = 0; // OK. this is not in a constructor.}}Copy the code

Limits the number of exceptions that can be thrown (no-throw-literal)

This rule aims to keep exception throws consistent by disallowing literal and expressions that cannot be Error objects.

'no-throw-literal': 'warn'
Copy the code
  • Rating: “warn”
Examples of incorrect code for this rule:
/*eslint no-throw-literal: "error"*/
/*eslint-env es6*/

throw "error";

throw 0;

throw undefined;

throw null;

var err = new Error(a);throw "an " + err;
// err is recast to a string literal

var err = new Error(a);throw `${err}`;
Copy the code
Examples of correct code for this rule:
/*eslint no-throw-literal: "error"*/

throw new Error(a);throw new Error("error");

var e = new Error("error");
throw e;

try {
  throw new Error("error");
} catch (e) {
  throw e;
}
Copy the code

Disable undeclared variables (no-undef)

References to any undeclared variable will raise a warning unless explicitly in /global… / comments.

'no-undef': 'error'
Copy the code
  • Rating: “error”
Examples of incorrect code for this rule:
/*eslint no-undef: "error"*/

var a = someFunction();
b = 10;
Copy the code
Examples of correct code for this rule with a global declaration:
//*global someFunction b:true*/
/*eslint no-undef: "error"*/

var a = someFunction();
b = 10;
Copy the code
Examples of incorrect code for this rule with a global declaration:
/*global b*/
/*eslint no-undef: "error"*/

b = 10;
Copy the code

Disable specific globals (no-restricted-globals)

This rule allows you to specify the names of global variables that you do not want to use in your application.

'no-restricted-globals': ['error'].concat(restrictedGlobals)
Copy the code
  • Rating: “error”
  • The option “restrictedGlobals” is a global variable
Examples of incorrect code for this rule with global variables “event”, “fdescribe” :
/*global event, fdescribe*/
/*eslint no-restricted-globals: ["error", "event", "fdescribe"]*/

function onClick() {
  console.log(event);
}

fdescribe("foo".function () {});
Copy the code
Examples of correct code for this rule for the global variable “event” :
/*global event*/
/*eslint no-restricted-globals: ["error", "event"]*/

import event from "event-module";
/*global event*/
/*eslint no-restricted-globals: ["error", "event"]*/

var event = 1;
Copy the code

Disallow confusing multiline expressions (no-unexpect-multiline)

This rule disallows confusing multi-line expressions.

'no-unexpected-multiline': 'warn'
Copy the code
  • Rating: “warn”
Examples of incorrect code for this rule:
/*eslint no-unexpected-multiline: "error"*/

var foo = bar(1 || 2).baz();

var hello = "world"[(1.2.3)].forEach(addNumber);

let x = (function () {})`hello`;

let x = function () {};
x`hello`;

let x = foo / regex / g.test(bar);
Copy the code
Examples of correct code for this rule:
var foo = bar;
(1 || 2).baz();

var foo = bar;
(1 || 2).baz();

var hello = "world";
[1.2.3].forEach(addNumber);

var hello = "world";
void [1.2.3].forEach(addNumber);

let x = function () {};
`hello`;

let tag = function () {};
tag`hello`;
Copy the code

Disallow confusing multiline expressions (no-unexpect-multiline)

This rule disallows unreachable code after return, throw, continue, and break statements.

'no-unexpected-multiline': 'warn'
Copy the code
  • Rating: “warn”
Examples of incorrect code for this rule:
/*eslint no-unreachable: "error"*/

function foo() {
  return true;
  console.log("done");
}

function bar() {
  throw new Error("Oops!");
  console.log("done");
}

while (value) {
  break;
  console.log("done");
}

throw new Error("Oops!");
console.log("done");

function baz() {
  if (Math.random() < 0.5) {
    return;
  } else {
    throw new Error(a); }console.log("done");
}

for (;;) {}
console.log("done");
Copy the code
Examples of correct code for this rule:
/*eslint no-unreachable: "error"*/

function foo() {
  return bar();
  function bar() {
    return 1; }}function bar() {
  return x;
  var x;
}

switch (foo) {
  case 1:
    break;
    var x;
}
Copy the code

Disallow unused expressions (no-unused-expressions)

The goal of this rule is to eliminate unused expressions that have no effect in your program. This rule does not apply to function or constructor calls that use the new operator, as they may have side effects

'no-unused-expressions': [
  'warn',
  {
    allowShortCircuit: true.allowTernary: true.allowTaggedTemplates: true,},]Copy the code
  • Rating: “warn”
  • The option “allowShortCircuit”: set to true will allow you to use logic short-circuit evaluation in expressions. (Default: false)
  • The option “allowTernary”: set to true will allow you to use ternary operators like logical short-circuit evaluation in your expressions. (Default: false).
  • The “allowTaggedTemplates” option: set to true will allow you to use tagged template literals in expressions (default: false).
Examples of incorrect code for this rule with the {“allowShortCircuit”: true} option:
/*eslint no-unused-expressions: ["error", { "allowShortCircuit": true }]*/

a || b;
Copy the code
Examples of correct code for this rule with the {“allowShortCircuit”: true} option:
/*eslint no-unused-expressions: ["error", { "allowShortCircuit": true }]*/

a && b();
a() || (b = c);
Copy the code
Examples of incorrect code for this rule with the {“allowTernary”: true} option:
/*eslint no-unused-expressions: ["error", { "allowTernary": true }]*/

a ? b : 0;
a ? b : c();
Copy the code
Examples of correct code for this rule with the {“allowTernary”: true} option:
/*eslint no-unused-expressions: ["error", { "allowTernary": true }]*/

a ? b() : c();
a ? (b = c) : d();
Copy the code
Examples of incorrect code for this rule with the {“allowTaggedTemplates”: true} option:
/*eslint no-unused-expressions: ["error", { "allowTaggedTemplates": true }]*/

`some untagged template string`;
Copy the code
Examples of correct code for this rule with the {“allowTaggedTemplates”: true} option:
/*eslint no-unused-expressions: ["error", { "allowTaggedTemplates": true }]*/

tag`some tagged template string`;
Copy the code

Disallow unused labels (no-unused-labels)

The –fix option on the command line automatically fixes some of the problems reported by this rule.

This rule is designed to eliminate unused labels.

'no-unused-labels': 'warn'
Copy the code
  • Rating: “warn”
Examples of incorrect code for this rule:
/*eslint no-unused-labels: "error"*/

A: var foo = 0;

B: {
  foo();
}

C: for (let i = 0; i < 10; ++i) {
  foo();
}
Copy the code
Examples of correct code for this rule:
/*eslint no-unused-labels: "error"*/

A: {
  if (foo()) {
    break A;
  }
  bar();
}

B: for (let i = 0; i < 10; ++i) {
  if (foo()) {
    break B;
  }
  bar();
}
Copy the code

Disallow (no-use-before-define)

A warning is reported when an identifier is used that has not yet been declared.

'no-use-before-define': [
  'warn',
  {
    functions: false.classes: false.variables: false,},]Copy the code
  • Rating: “warn”
  • Option “functions”: This argument indicates whether the rule checks for function declarations. If the argument is true, this rule alerts when a reference to an undeclared function is made. Otherwise, ignore these references. It is safe to do so because the function declaration scope is promoted. The default value is true.
  • Option “classes”: This parameter indicates whether to check for class declarations in the upper scope. If the argument is true, this rule alerts you when you reference an undeclared class. Otherwise, this rule ignores references to class declarations in the upper scope. Because the class declaration scope is not promoted, doing so can be dangerous. The default parameter is true.
  • Option “variables”: This parameter indicates whether to detect variable declarations in the upper scope. If the argument is true, this rule alerts when a reference to an undeclared variable is made. Otherwise, this rule ignores references to variable declarations in the upper scope, but still reports references to variable declarations in the same scope. The default parameter is true.
Examples of correct code for this rule with the {“functions”: false} option:
/*eslint no-use-before-define: ["error", { "functions": false }]*/

f();
function f() {}
Copy the code
Examples of incorrect code for this rule with the {“classes”: false} option:
/*eslint no-use-before-define: ["error", { "classes": false }]*/
/*eslint-env es6*/

new A();
class A {}
Copy the code
Examples of correct code for this rule with the {“classes”: false} option:
/*eslint no-use-before-define: ["error", { "classes": false }]*/
/*eslint-env es6*/

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

class A {}
Copy the code
Examples of incorrect code for this rule with the {“variables”: false} option:
/*eslint no-use-before-define: ["error", { "variables": false }]*/

console.log(foo);
var foo = 1;
Copy the code
Examples of correct code for this rule with the {“variables”: false} option:
/*eslint no-use-before-define: ["error", { "variables": false }]*/

function baz() {
  console.log(foo);
}

var foo = 1;
Copy the code

Do not allow unnecessary computation-attribute keys on objects (no-useless-computed-key)

The –fix option on the command line automatically fixes some of the problems reported by this rule.

This rule does not allow unnecessary use of computed property keys.

'no-useless-computed-key': 'warn'
Copy the code
  • Rating: “warn”
Examples of incorrect code for this rule:
/*eslint-env es6*/

var a = { ["0"] :0 };
var a = { ["0 + 1234"] :0 };
var a = { [0] :0 };
var a = { ["x"] :0 };
var a = { ["x"() {}};Copy the code
Examples of correct code for this rule:
/*eslint no-useless-computed-key: "error"*/

var c = { a: 0 };
var c = { 0: 0 };
var a = { x() {} };
var c = { a: 0 };
var c = { "0 + 1234": 0 };
Copy the code

Disallow unnecessary concatenation of characters (no-useless-concat)

This rule is intended to mark the concatenation of two literals that can be combined into a single literal. Literals can be strings or template literals.

'no-useless-concat': 'warn'
Copy the code
  • Rating: “warn”
Examples of incorrect code for this rule:
/*eslint no-useless-concat: "error"*/
/*eslint-env es6*/

// these are the same as "10"
var a = `some` + `string`;
var a = "1" + "0";
var a = "1" + ` 0 `;
var a = 1 ` ` + "0";
var a = 1 ` ` + ` 0 `;
Copy the code
Examples of correct code for this rule:
/*eslint no-useless-concat: "error"*/

// when a non string is included
var c = a + b;
var c = "1" + a;
var a = 1 + "1";
var c = 1 - 2;
// when the string concatenation is multiline
var c = "foo" + "bar";
Copy the code

Disallow unnecessary constructors (no-useless-constructor)

This rule marks constructors that can be safely removed without changing the behavior of the class.

'no-useless-constructor': 'warn'
Copy the code
  • Rating: “warn”
Examples of incorrect code for this rule:
/*eslint no-useless-constructor: "error"*/
/*eslint-env es6*/

class A {
  constructor() {}}class A extends B {
  constructor(... args) {super(...args);
  }
}
Copy the code
Examples of correct code for this rule:
/*eslint no-useless-constructor: "error"*/

class A {}

class A {
  constructor() { doSomething(); }}class A extends B {
  constructor() {
    super("foo"); }}class A extends B {
  constructor() {
    super();
    doSomething();
  }
}
Copy the code

Disallow unnecessary escape (no-useless-escape)

This rule marks escapes that can be safely removed without changing the behavior of the code.

'no-useless-escape': 'warn'
Copy the code
  • Rating: “warn”
Examples of incorrect code for this rule:
/*eslint no-useless-escape: "error"*/

"\ '";
'\ "';
"\ #";
"\e";
` ` \";
` \"${foo}\ "`;
`\#{foo}`;
/ \! /;
/ / @ /;
Copy the code
Examples of correct code for this rule:
/*eslint no-useless-escape: "error"*/

"\" ";
'\' ';
"\x12";
"\u00a9";
"\ 371";
"xs\u2111";
` \ ` `;
` \ ${${foo}The \} `;
` $\ {${foo}The \} `;
/\\/g;
/\t/g;
/\w\$\*\^\./;
Copy the code

Disallow renaming import, export, and Destructured Assignments to the same name (no-useless-rename)

This rule does not allow import, export, and Destructured Assignments to be renamed to the same name.

'no-useless-rename': [
  'warn',
  {
    ignoreDestructuring: false.ignoreImport: false.ignoreExport: false,},]Copy the code
  • Rating: “warn”
  • Option “ignoreDestructuring”: set to false. This rule checks destructuring assignments (default)
  • Option “ignoreImport”: set to false for this time, this rule checks imports (default)
  • Option “ignoreExport”: set to false for this time, this rule checks exports (default)
Examples of incorrect code for this rule by default:
/*eslint no-useless-rename: "error"*/

import { foo } from "bar";
export { foo };
export { foo } from "bar";
let { foo: foo } = bar;
let { foo: foo } = bar;
function foo({ bar: bar }) {}
({ foo: foo }) => {};
Copy the code
Examples of correct code for this rule by default:
/*eslint no-useless-rename: "error"*/

import * as foo from "foo";
import { foo } from "bar";
import { foo as bar } from "baz";

export { foo };
export { foo as bar };
export { foo as bar } from "foo";

let { foo } = bar;
let { foo: bar } = baz;
let { [foo]: foo } = bar;

function foo({ bar }) {}
function foo({ bar: baz }) {}

({ foo }) => {};
({ foo: bar }) = > {};
Copy the code

Disable the with statement (no-with)

This rule is intended to exclude with statements.

If ESLint parses code in strict mode, the parser (not this rule) will report such an error.

'no-with': 'warn'
Copy the code
  • Rating: “warn”
Examples of incorrect code for this rule:
/*eslint no-with: "error"*/

with (point) {
  r = Math.sqrt(x * x + y * y); // is r a member of point?
}
Copy the code
Examples of correct code for this rule:
/*eslint no-with: "error"*/
/*eslint-env es6*/

const r = ({ x, y }) = > Math.sqrt(x * x + y * y);
Copy the code

Disallow whitespace before properties (no-whitespace-before-property)

The –fix option on the command line automatically fixes some of the problems reported by this rule.

Rule Description This rule disallows whitespace around a dot or before an open parenthesis before an object property. This rule allows whitespace if the object and property are not on the same line, in which case it is common to add a new line to a cascaded property.

'no-whitespace-before-property': 'warn'
Copy the code
  • Rating: “warn”
Examples of incorrect code for this rule:
/*eslint no-whitespace-before-property: "error"*/

foo[bar];

foo.bar;

foo.bar;

foo.bar.baz;

foo.bar().baz();

foo.bar().baz();
Copy the code
Examples of correct code for this rule:
/*eslint no-whitespace-before-property: "error"*/

foo.bar;

foo[bar];

foo[bar];

foo.bar.baz;

foo.bar().baz();

foo.bar().baz();

foo.bar().baz();
Copy the code

The radix is required.

This rule is designed to prevent uncertain string to number conversions or redundant base 10 in modern environments.

'radix': 'warn'
Copy the code
  • Rating: “warn”
Examples of incorrect code for this rule:
/*eslint radix: "error"*/

var num = parseInt("071");

var num = parseInt(someValue);

var num = parseInt("071"."abc");

var num = parseInt(a);Copy the code
Examples of correct code for this rule:
/*eslint radix: "error"*/

var num = parseInt("071".10);

var num = parseInt("071".8);

var num = parseFloat(someValue);
Copy the code

Disable generator functions without yield in functions (require-yield)

If there is no yield keyword inside the generator function, this rule will issue a warning.

'radix': 'warn'
Copy the code
  • Rating: “warn”
Examples of incorrect code for this rule:
/*eslint require-yield: "error"*/
/*eslint-env es6*/

function* foo() {
  return 10;
}
Copy the code
Examples of correct code for this rule:
/*eslint require-yield: "error"*/
/*eslint-env es6*/

function* foo() {
  yield 5;
  return 10;
}

function foo() {
  return 10;
}

// This rule does not warn on empty generator functions.
function* foo() {}
Copy the code

Enforce limits on spacing between extension operators and their expressions (REST-spread-spacing)

The –fix option on the command line automatically fixes some of the problems reported by this rule.

The purpose of this rule is to enforce limits on spacing between extension operators and their expressions. This rule also allows the current object to extend attributes when enabled.

'rest-spread-spacing': ['warn'.'never']
Copy the code
  • Rating: “warn”
  • Option “never”: (default) no Spaces are allowed between the extension operator and its expression.
Examples of incorrect code for this rule “never” :
/*eslint rest-spread-spacing: ["error", "never"]*/

fn(... args)
[... arr, 4.5.6]
let [a, b, ... arr] = [1.2.3.4.5];
function fn(. args) { console.log(args); }
let { x, y, ... z } = { x: 1.y: 2.a: 3.b: 4 };
let n = { x, y, ... z };
Copy the code
Examples of correct code for this rule “never” :
/*eslint rest-spread-spacing: ["error", "never"]*/fn(... args) [...arr,4.5.6]
let [a, b, ...arr] = [1.2.3.4.5];
function fn(. args) { console.log(args); }
let{ x, y, ... z } = {x: 1.y: 2.a: 3.b: 4 };
letn = { x, y, ... z };Copy the code

Requires or disallows the use of strict mode directives (strict)

The –fix option on the command line automatically fixes some of the problems reported by this rule.

This rule either requires or disallows strict mode directives.

strict: ["warn"."never"];
Copy the code
  • Rating: “warn”
  • Option “never”: disables the strict mode directive
Examples of incorrect code for this rule with the “never” option:
/*eslint strict: ["error", "never"]*/

"use strict";

function foo() {}
/*eslint strict: ["error", "never"]*/

function foo() {
  "use strict";
}
Copy the code
Examples of correct code for this rule with the “never” option:
/*eslint strict: ["error", "never"]*/

function foo() {}
Copy the code

Requires or disallows Unicode byte order notation (BOM) (Unicode-BOM)

The –fix option on the command line automatically fixes some of the problems reported by this rule.

If the “always” option is used, this rule requires that files always start with the Unicode BOM character U+FEFF. If “never”, the file must never start with U+FEFF.

'unicode-bom': ['warn'.'never']
Copy the code
  • Rating: “warn”
  • Option “never”: (default) files cannot start with Unicode BOM
Examples of incorrect code for this rule with the “never” option:
/*eslint unicode-bom: ["error", "never"]*/

U + FEFF;
var abc;
Copy the code
Examples of correct code for this rule with the “never” option:
/*eslint unicode-bom: ["error", "never"]*/

var abc;
Copy the code

Requires calling isNaN() to check NaN(use-isnan)

This rule disallows comparisons with ‘NaN’.

'use-isnan': 'warn'
Copy the code
  • Rating: “warn”
Examples of incorrect code for this rule:
/*eslint use-isnan: "error"*/

if (foo == NaN) {
  // ...
}

if(foo ! =NaN) {
  // ...
}
Copy the code
Examples of correct code for this rule:
/*eslint use-isnan: "error"*/

if (isNaN(foo)) {
  // ...
}

if (!isNaN(foo)) {
  // ...
}
Copy the code

Enforces typeof expressions to be compared to valid strings (valid-typeof)

This rule enforces typeof expressions to be compared to valid strings.

'valid-typeof': 'warn'
Copy the code
  • Rating: “warn”
Examples of incorrect code for this rule:
/*eslint valid-typeof: "error"*/

typeof foo === "strnig";
typeof foo == "undefimed";
typeofbar ! ="nunber";
typeofbar ! = ="fucntion";
Copy the code
Examples of correct code for this rule:
/*eslint valid-typeof: "error"*/

typeof foo === "string";
typeof bar == "undefined";
typeof foo === baz;
typeof bar === typeof qux;
Copy the code

Disallow certain object properties (no-restricted-properties)

This rule looks for access to a given property key on a given object name, either when reading the property’s value or when calling it as a function. You can specify an optional message indicating an alternative API or restriction reason.

'no-restricted-properties': [
  'error',
  {
    object: 'System'.property: 'import'.message: 'Please use import() instead.',},]Copy the code
  • Rating: “error”
  • Option “object”: disallowed class name
  • Option “property”: disallowed property name
  • Option “message”: prompt message

import/first

This rule reports any imports that follow a non-import statement.

'import/first': 'error'
Copy the code
  • Rating: “error”
Examples of incorrect code for this rule:
import foo from "./foo";

// some module-level initializer
initWith(foo);

import bar from "./bar"; // <- reported
Copy the code
Examples of correct code for this rule:
import foo from "./foo";
import bar from "./bar";

// some module-level initializer
initWith(foo);
Copy the code

import/no-amd

Module-scoped report require([array],…) And define ([array],…). Function calls. If the parameter! = 2 does not warn, or the first argument is not an array of strings.

'import/no-amd': 'error'
Copy the code
  • Rating: “error”
Examples of incorrect code for this rule:
Define ([" a ", "b"], function (" a ", "b") {/ *... * /}) require ([" b ", "c"], function (b, c) {/ *... * /})Copy the code

import/no-webpack-loader-syntax

Disables the use of Webpack loader syntax in imports

'import/no-webpack-loader-syntax': 'error'
Copy the code
  • Rating: “error”
Examples of incorrect code for this rule:
import myModule from "my-loader! my-module";
import theme from "style! css! ./theme.css";

var myModule = require("my-loader! ./my-module");
var theme = require("style! css! ./theme.css");
Copy the code
Examples of correct code for this rule:
import myModule from "my-module";
import theme from "./theme.css";

var myModule = require("my-module");
var theme = require("./theme.css");
Copy the code

Prevent comments from being inserted as textnodes (react/jsx-no-comment-textnodes)

This rule prevents comment strings (for example, starting with // or /*) from being accidentally injected as text nodes in JSX statements.

'react/jsx-no-comment-textnodes': 'warn'
Copy the code
  • Rating: “warn”
Examples of incorrect code for this rule:
var Hello = createReactClass({
  render: function () {
    return <div>// empty div</div>; }});var Hello = createReactClass({
  render: function () {
    return <div>/* empty div */</div>; }});Copy the code
Examples of correct code for this rule:
var Hello = createReactClass({
  displayName: 'Hello'.render: function() {
    return <div>{/* empty div */}</div>; }});var Hello = createReactClass({
  displayName: 'Hello'.render: function() {
    return <div/ *empty div* / ></div>; }});var Hello = createReactClass({
  displayName: 'Hello'.render: function() {
    return <div className={'foo' /* temp class* /} < /div>; }});Copy the code

Disallow duplicate properties in JSX (react/jsx-no-duplicate props)

Creating JSX elements using duplicate props can cause unexpected behavior in your application.

'react/jsx-no-duplicate-props': ['warn', { ignoreCase: true }]
Copy the code
  • Rating: “warn”
  • Option “ignoreCase”: ignores case. The default is false.
Examples of incorrect code for this rule:
< Hello name = "John" name = "John" />;Copy the code
Examples of correct code for this rule:
< Hello firstname = "John" lastname = "Doe" />;Copy the code

# target=’_blank'(react/jsx-no-target-blank)

Do not use unsafe target=’_blank’ (outside chain)

'react/jsx-no-target-blank': 'warn'
Copy the code
  • Rating: “warn”
Examples of incorrect code for this rule:
var Hello = <a target="_blank" href="http://example.com/"></a>;
Copy the code
Examples of correct code for this rule:
var Hello = <p target="_blank"></p>;
var Hello = (
  <a target="_blank" rel="noopener noreferrer" href="http://example.com"></a>
);
var Hello = <a target="_blank" href="relative/path/in/the/host"></a>;
var Hello = <a target="_blank" href="/absolute/path/in/the/host"></a>;
var Hello = <a></a>;
Copy the code

Disallow undeclared variables in JSX (react/jsx-no-undef)

Undeclared variables are disallowed in JSX

'react/jsx-no-undef': 'error'
Copy the code
  • Rating: “error”
Examples of incorrect code for this rule:
<Hello name="John"/ >;// will ignore Text in the global scope and warn
var Hello = React.createClass({
  render: function () {
    return <Text>Hello</Text>; }});module.exports = Hello;
Copy the code
Examples of correct code for this rule:
var Hello = require("./Hello");

<Hello name="John" />;
Copy the code

(jSX-A11Y/Anchor -has-content)

The force anchor has content that the screen reader can access. Accessibility means it won’t be hidden using the Aria-hidden item.

'jsx-a11y/anchor-has-content': 'warn'
Copy the code
  • Rating: “warn”
Examples of incorrect code for this rule:
<a />
<a><TextWrapper aria-hidden /></a>
Copy the code
Examples of correct code for this rule:
<a>Anchor Content!</a>
<a><TextWrapper /><a>
<a dangerouslySetInnerHTML={{ __html: 'foo' }} />
Copy the code

Jsx-a11y /aria-activedescendant-has- TabIndex

Aria-active Descendant is used to manage focus in a composite widget. The element aria-ActiveDescendant with this attribute preserves the active document focus; It indicates which of its child elements has a secondary focus Aria-Active descendant by assigning the element’s ID to the value. This pattern is used to build a list of choices like search types. The search input box retains the document focus so that the user can type input. If you press the down arrow key and highlight the search suggestion, the ID of the suggestion element is applied as the value of the ARIa-Active Descendant input element.

Since an element aria-ActiveDescendant must be magnifyable, it must have a zero inherent in the tabIndex or the tabIndex must declare a zero with the tabIndex attribute.

'jsx-a11y/aria-activedescendant-has-tabindex': 'warn'
Copy the code
  • Rating: “warn”
Examples of incorrect code for this rule:
<div aria-activedescendant={someID} />
<div aria-activedescendant={someID} tabIndex={-1} />
<div aria-activedescendant={someID} tabIndex="-1" />
<input aria-activedescendant={someID} tabIndex={-1} />
Copy the code
Examples of correct code for this rule:
<CustomComponent />
<CustomComponent aria-activedescendant={someID} />
<CustomComponent aria-activedescendant={someID} tabIndex={0} />
<CustomComponent aria-activedescendant={someID} tabIndex={-1} />
<div />
<input />
<div tabIndex={0} />
<div aria-activedescendant={someID} tabIndex={0} />
<div aria-activedescendant={someID} tabIndex="0" />
<div aria-activedescendant={someID} tabIndex={1} />
<input aria-activedescendant={someID} />
<input aria-activedescendant={someID} tabIndex={0} />
Copy the code

Elements cannot use invalid ARIA attributes (jsx-a11y/aria-props)

Elements cannot use invalid ARIA attributes. If you find an attribute that is not listed in ARIA -* in the Wai-ARIA state and attribute specification, you will fail.

'jsx-a11y/aria-props': 'warn'
Copy the code
  • Rating: “warn”
Examples of incorrect code for this rule:
<! -- Bad: Labeled using incorrectly spelled aria-labeledby --><div id="address_label">Enter your address</div>
<input aria-labeledby="address_label">
Copy the code
Examples of correct code for this rule:
<! -- Good: Labeled using correctly spelled aria-labelledby --><div id="address_label">Enter your address</div>
<input aria-labelledby="address_label">
Copy the code

Aria state and attribute values must be valid (JSX-A11Y/aria-Proptypes)

Aria state and attribute values must be valid

'jsx-a11y/aria-proptypes': 'warn'
Copy the code
  • Rating: “warn”
Examples of incorrect code for this rule:
<! -- Bad: the aria-hidden state isof type true/false -->
<span aria-hidden="yes">foo</span>
Copy the code
Examples of correct code for this rule:
<! -- Good: the aria-hidden state isof type true/false -->
<span aria-hidden="true">foo</span>
Copy the code

The element must use a valid ARIA role (jsx-a11y/aria-role) (#jsx-a11y/aria-props)

Elements with ARIA roles must use valid, non-abstract ARIA roles.

'jsx-a11y/aria-role': 'warn'
Copy the code
  • Rating: “warn”
Examples of incorrect code for this rule:
<div role="datepicker"></div><! -- Bad:"datepicker" is not an ARIA role -->
<div role="range"></div><! -- Bad:"range" is an _abstract_ ARIA role -->
<div role=""></div><! -- Bad: An empty ARIA role is not allowed --><Foo role={role}></Foo><! -- Bad: ignoreNonDOM is set tofalse or not set -->
Copy the code
Examples of correct code for this rule:
<div role="button"></div><! -- Good:"button" is a valid ARIA role -->
<div role={role}></div><! -- Good: role is a variable & cannot be determined until runtime. --><div></div><! -- Good: No ARIA role --><Foo role={role}></Foo><! -- Good: ignoreNonDOM is set totrue -->
Copy the code

Jsx-a11y/ARIa-unsupported elements

Some reserved DOM elements do not support ARIA roles, states, and attributes. This is often because they are not visible, such as Meta, HTML, Script, style. This rule enforces that these DOM elements do not contain roles and/or aria-* props.

'jsx-a11y/aria-unsupported-elements': 'warn'
Copy the code
  • Rating: “warn”
Examples of incorrect code for this rule:
<! -- Bad: the meta element should not be given any ARIA attributes --><meta charset="UTF-8" aria-hidden="false" />
Copy the code
Examples of correct code for this rule:
<! -- Good: the meta element should not be given any ARIA attributes --><meta charset="UTF-8" />
Copy the code

Jsx-a11y /heading-has-content

Enforces header elements (H1, H2, etc.) to be accessed for the content and the content’s screen reader. Accessibility means it will not be hidden using aria-hidden Prop.

'jsx-a11y/heading-has-content': 'warn'
Copy the code
  • Rating: “warn”
Examples of incorrect code for this rule:
<h1 />
<h1><TextWrapper aria-hidden />
Copy the code
Examples of correct code for this rule:
<h1>Heading Content!</h1>
<h1><TextWrapper /><h1>
<h1 dangerouslySetInnerHTML={{ __html: 'foo' }} />
Copy the code

# # # # # # #

Iframe title (jsX-A11y /iframe-has-title)

The

'jsx-a11y/iframe-has-title': 'warn'
Copy the code
  • Rating: “warn”
Examples of incorrect code for this rule:
<iframe /> <iframe {... props} /> <iframe title="" /> <iframe title={''} /> <iframe title={``} /> <iframe title={undefined} /> <iframe title={false} /> <iframe title={true} /> <iframe title={42} />Copy the code
Examples of correct code for this rule:
<iframe title="This is a unique title" />
<iframe title={uniqueTitle} />
Copy the code

Img-redundant -alt (jsx-a11y/img-redundant- Alt)

Force the IMG Alt attribute to contain no word image, picture, or photo. The screen reader has declared the IMG element as a picture. There is no need to use text such as images, photos and/or pictures.

'jsx-a11y/img-redundant-alt': 'warn'
Copy the code
  • Rating: “warn”
Examples of incorrect code for this rule:
<img src="foo" alt="Photo of foo being weird." />
<img src="bar" alt="Image of me at a bar!" />
<img src="baz" alt="Picture of baz fixing a bug." />
Copy the code
Examples of correct code for this rule:
<img src="foo" alt="Foo eating a sandwich." />
<img src="bar" aria-hidden alt="Picture of me taking a photo of an image" /> // Will pass because it is hidden.
<img src="baz" alt={`Baz taking a ${photo}`} /> // This is valid since photo is a variable name.
Copy the code

Href must be valid (jsx-a11y/ hall-no-hash)

A link AN HTML element with a valid href attribute is formally defined to represent a hyperlink. That is, a link between one HTML document and another HTML document, or between a location in an HTML document and another location within the same document.

'jsx-a11y/href-no-hash': 'warn'
Copy the code
  • Rating: “warn”
Examples of incorrect code for this rule:
/*Anchors should be a button:*/
<a onClick={foo} />
<a href="#" onClick={foo} />
<a href={"#"} onClick={foo} />
<a href={`#`} onClick={foo} />
<a href="javascript:void(0)" onClick={foo} />
<a href={"javascript:void(0)"} onClick={foo} /> <a href={`javascript:void(0)`} onClick={foo} /> /*Missing href attribute:*/ <a /> <a href={undefined}  /> <a href={null} /> /*Invalid href attribute:*/ <a href="#" />
<a href={"#"} />
<a href={`# `} / >
<a href="javascript:void(0)" />
<a href={"javascript:void(0)"} />
<a href={`javascript:void(0)`} />
Copy the code
Examples of correct code for this rule:
<a href="https://github.com" />
<a href="#section" />
<a href="foo" />
<a href="/foo/bar" />
<a href={someValidPath} />
<a href="https://github.com" onClick={foo} />
<a href="#section" onClick={foo} />
<a href="foo" onClick={foo} />
<a href="/foo/bar" onClick={foo} />
<a href={someValidPath} onClick={foo} />
Copy the code

# # # # # # #

Disable access-key (jSX-A11y /no-access-key)

Forces the element to have no accessKey Prop. Access keys are HTML attributes that allow Web developers to assign keyboard shortcuts to elements. Inconsistencies between keyboard shortcuts and keyboard commands used by screen readers and keyboards can create frictionless complexity, so to avoid complexity, shortcuts should not be used.

'jsx-a11y/no-access-key': 'warn'
Copy the code
  • Rating: “warn”
Examples of incorrect code for this rule:
<div accessKey="h" />
Copy the code
Examples of correct code for this rule:
<div />
Copy the code

Jsx-a11y/no-mothmot-elements: mothmot-elements (jsx-a11y/ no-mothmot-elements)

These elements are likely to be deprecated and should be avoided. By default, the following elements are visually distracting:

and

.

'jsx-a11y/no-distracting-elements': 'warn'
Copy the code
  • Rating: “warn”
Examples of incorrect code for this rule:
<marquee />
<blink />
Copy the code
Examples of correct code for this rule:
<div />
Copy the code

Disable redundant roles (jsx-A11y /no-redundant roles)

Some HTML elements have local semantics implemented by the browser. This includes default/implied ARIA roles. Setting an ARIA role that matches its default/implied role is redundant because it has already been set by the browser.

'jsx-a11y/no-redundant-roles': 'warn'
Copy the code
  • Rating: “warn”
Examples of incorrect code for this rule:
<button role="button" />
<img role="img" src="foo.jpg" />
Copy the code
Examples of correct code for this rule:
<div />
<button role="presentation" />
<MyComponent role="main" />
Copy the code

Role required aria props (jsx-a11y/role-has-required-aria-props)

An element with an ARIA role must have all the required attributes for that role.

'jsx-a11y/role-has-required-aria-props': 'warn'
Copy the code
  • Rating: “warn”
Examples of incorrect code for this rule:
<! -- Bad: the checkbox role requires the aria-checked state --><span role="checkbox" aria-labelledby="foo" tabindex="0"></span>
Copy the code
Examples of correct code for this rule:
<! -- Good: the checkbox role requires the aria-checked state --><span role="checkbox" aria-checked="false" aria-labelledby="foo" tabindex="0"></span>
Copy the code

Role-supports -aria-props (jsx-a11y/role-supports-aria-props)

An element that enforces an explicit or implicit role contains only the attribute ROLE supported by ARIA -*. Many ARIA attributes (states and attributes) can only be used for elements with specific roles. Some elements have an implicit role, such as , which resolves to role=”link”.

'jsx-a11y/role-supports-aria-props': 'warn'
Copy the code
  • Rating: “warn”
Examples of incorrect code for this rule:
<! -- Bad: the radio role does not support the aria-required property --><ul role="radiogroup" aria-labelledby="foo">
    <li aria-required tabIndex="1" role="radio" aria-checked="false">Rainbow Trout</li>
    <li aria-required tabIndex="1" role="radio" aria-checked="false">Brook Trout</li>
    <li aria-required tabIndex="0" role="radio" aria-checked="true">Lake Trout</li>
</ul>
Copy the code
Examples of correct code for this rule:
<! -- Good: the radiogroup role does support the aria-required property --><ul role="radiogroup" aria-required aria-labelledby="foo">
    <li tabIndex="1" role="radio" aria-checked="false">Rainbow Trout</li>
    <li tabIndex="1" role="radio" aria-checked="false">Brook Trout</li>
    <li tabIndex="0" role="radio" aria-checked="true">Lake Trout</li>
</ul>
Copy the code

Jsx-a11y/Scope

The scope of scope should only be used on < th > elements.

'jsx-a11y/scope': 'warn'
Copy the code
  • Rating: “warn”
Examples of incorrect code for this rule:
<div scope />
Copy the code
Examples of correct code for this rule:
<th scope="col" />
<th scope={scope} />
Copy the code

Disable isMounted (React/no-is-Mounted)

IsMounted is an anti-pattern that is not available when using the ES6 class and is being officially deprecated.

'react/no-is-mounted': 'warn'
Copy the code
  • Rating: “warn”
Examples of incorrect code for this rule:
var Hello = createReactClass({
  handleClick: function () {
    setTimeout(function () {
      if (this.isMounted()) {
        return; }}); },render: function () {
    return <div onClick={this.handleClick.bind(this)}>Hello</div>; }});Copy the code
Examples of correct code for this rule:
var Hello = createReactClass({
  render: function () {
    return <div onClick={this.props.handleClick}>Hello</div>; }});Copy the code

Force ES5 or ES6 classes to return values in the render function (react/require-render-return)

When Render writes methods in a component, it’s easy to forget to return JSX content. This rule will warn if return declarations are missing.

'react/require-render-return': 'error'
Copy the code
  • Rating: “error”
Examples of incorrect code for this rule:
var Hello = createReactClass({ render() { <div>Hello</div>; }}); class Hello extends React.Component { render() { <div>Hello</div>; }}Copy the code
Examples of correct code for this rule:
var Hello = createReactClass({
  render() {
    return <div>Hello</div>; }});class Hello extends React.Component {
  render() {
    return <div>Hello</div>; }}Copy the code

Style property values are enforced as objects (react/style-prop-object)

Requires the value style of prop to be an object or a variable of an object.

'react/style-prop-object': 'warn'
Copy the code
  • Rating: “warn”
Examples of incorrect code for this rule:
<div style="color: 'red'" />

<div style={true} />

<Hello style={true} />

const styles = true;
<div style={styles} />
React.createElement("div", { style: "color: 'red'" });

React.createElement("div", { style: true });

React.createElement("Hello", { style: true });

const styles = true;
React.createElement("div", { style: styles });
Copy the code
Examples of correct code for this rule:
<div style={{ color: "red" }} />

<Hello style={{ color: "red" }} />

const styles = { color: "red" };
<div style={styles} />
React.createElement("div", { style: { color: 'red' }});

React.createElement("Hello", { style: { color: 'red' }});

const styles = { height: '100px' };
React.createElement("div", { style: styles });
Copy the code

Access – Emoji (JSX-A11Y /accessible-emoji)

Emojis have become a common way to communicate content to end users. However, for the person using the screen reader, he/she may not even know this content is there. By wrapping the emoji in the screen reader, giving the role=”img” and providing the useful description aria-label, the screen reader treats the emoji as an image in the accessible tree and provides the end user with an accessible name.

'jsx-a11y/accessible-emoji': 'warn'
Copy the code
  • Rating: “warn”
Examples of incorrect code for this rule:
<span role="img" aria-label="Snowman">&#9731; <span role="img" aria-label="Panda">🐼</span> <span role="img" aria-labelledby="panda1">🐼</span>Copy the code
Examples of correct code for this rule:
< span > 🐼 < / span > < I role = "img" aria - label = "Panda" > 🐼 < / I >Copy the code

Alt-text (JSX-A11Y/Alt-text)

It is mandatory that all elements that need to replace text have meaningful information passed to the end user. This is an important part of accessibility for screen reader users, so that they understand how the content is used on the page. By default, this rule will check the following for replacement text: ,

, , and .

'jsx-a11y/alt-text': 'warn'
Copy the code
  • Rating: “warn”
Examples of incorrect code for this rule:
<img src="foo"/> <img {... props} /> <img {... props} alt /> // Has no value <img {... props} alt={undefined} /> // Has no value <img {... props} alt={`${undefined}`} /> // Has no value <img src="foo" role="presentation" /> // Avoid ARIA if it can be achieved  without <img src="foo" role="none" /> // Avoid ARIA if it can be achieved without <object {... props} /> <area {... props} /> <input type="image" {... props} />Copy the code
Examples of correct code for this rule:
<img src="foo" alt="Foo eating a sandwich." />
<img src="foo" alt={"Foo eating a sandwich."} />
<img src="foo" alt={altText} />
<img src="foo" alt={`${person} smiling`} />
<img src="foo" alt="" />

<object aria-label="foo" />
<object aria-labelledby="id1" />
<object>Meaningful description</object>
<object title="An object" />

<area aria-label="foo" />
<area aria-labelledby="id1" />
<area alt="This is descriptive!" />

<input type="image" alt="This is descriptive!" />
<input type="image" aria-label="foo" />
<input type="image" aria-labelledby="id1" />
Copy the code

Enforce PascalCase for user-defined JSX components (React/JSX-Pascal-Case)

Enforce the coding style defined and referenced in PascalCase by user-defined JSX components.

Note that since React’s JSX uses case conventions to distinguish between native component classes and HTML tags, this rule does not warn components that start with a lowercase letter.

'react/jsx-pascal-case': [
  'warn',
  {
    allowAllCaps: true.ignore: [],},]Copy the code
  • Rating: “warn”
  • Option “allowAllCaps”: Optional Boolean set to true to allow all uppercase component names (default is false).
  • Option “ignore”: An optional array of component names that can be ignored during validation

Prevents variables used in JSX from being incorrectly marked as unused (React/jSX-uses-vars)

Prevents variables used in JSX from being incorrectly marked as unused

'react/jsx-uses-vars': 'warn'
Copy the code
  • Rating: “warn”
Examples of incorrect code for this rule:
var Hello = require("./Hello");
Copy the code
Examples of correct code for this rule:
var Hello = require("./Hello");

<Hello name="John" />;
Copy the code

Prohibit children and props. DangerouslySetInnerHTML used at the same time the problem (the react/no – danger – with – the children)

This rule helps prevent due to use both the children and props. DangerouslySetInnerHTML and cause problems. React will issue a warning if this rule is ignored.

'react/no-danger-with-children': 'warn'
Copy the code
  • Rating: “warn”
Examples of incorrect code for this rule:
<div dangerouslySetInnerHTML={{ __html: "HTML" }}>
  Children
</div>

<Hello dangerouslySetInnerHTML={{ __html: "HTML" }}>
  Children
</Hello>
React.createElement("div", { dangerouslySetInnerHTML: { __html: "HTML" } }, "Children");

React.createElement("Hello", { dangerouslySetInnerHTML: { __html: "HTML" } }, "Children");
Copy the code
Examples of correct code for this rule:
<div dangerouslySetInnerHTML={{ __html: "HTML"}} / ><Hello dangerouslySetInnerHTML={{ __html: "HTML}} "/ >

<div>
  Children
</div>

<Hello>
  Children
</Hello>
React.createElement("div", { dangerouslySetInnerHTML: { __html: "HTML" } });

React.createElement("Hello", { dangerouslySetInnerHTML: { __html: "HTML" } });

React.createElement("div", {}, "Children");

React.createElement("Hello", {}, "Children");
Copy the code

Disallow use of deprecated methods (React /no-deprecated)

Several methods have been deprecated between React versions. This rule warns you if you try to use a method that is not recommended. Use share Settings to specify the React version.

'react/no-deprecated': 'warn'
Copy the code
  • Rating: “warn”
Examples of incorrect code for this rule:
React.render(<MyComponent />, root);

React.unmountComponentAtNode(root);

React.findDOMNode(this.refs.foo);

React.renderToString(<MyComponent />);

React.renderToStaticMarkup(<MyComponent />);

React.createClass({
  /* Class object */
});

const propTypes = {
  foo: PropTypes.bar,
};

//Any factories under React.DOM
React.DOM.div();

import React, { PropTypes } from "react";
Copy the code
Examples of correct code for this rule:
ReactDOM.render(<MyComponent />, root); // When [1, {"react": "0.13.0"}] reactdom.findDomNode (this.refs.foo); import { PropTypes } from "prop-types";Copy the code

Prohibit direct changes to this.state (react/no-direct-mutation-state)

Prevent this.state from changing directly, because a later call to setState() might replace the change you made. Think of this.state as immutable.

The only place you can assign this.state is in the ES6 class component constructor.

'react/no-direct-mutation-state': 'warn'
Copy the code
  • Rating: “warn”
Examples of incorrect code for this rule:
var Hello = createReactClass({
  componentDidMount: function () {
    this.state.name = this.props.name.toUpperCase();
  },
  render: function () {
    return <div>Hello {this.state.name}</div>; }});class Hello extends React.Component {
  constructor(props) {
    super(props);

    // Assign at instance creation time, not on a callback
    doSomethingAsync((a)= > {
      this.state = "bad"; }); }}Copy the code
Examples of correct code for this rule:
var Hello = createReactClass({
  componentDidMount: function() {
    this.setState({
      name: this.props.name.toUpperCase();
    });
  },
  render: function() {
    return <div>Hello {this.state.name}</div>; }});class Hello extends React.Component {
  constructor(props) {
    super(props)

    this.state = {
      foo: 'bar',}}}Copy the code

Prevent React from being incorrectly marked as unused (React/jsX-uses-react)

Prevent React from being incorrectly marked as unused

'react/jsx-uses-react': 'warn'
Copy the code
  • Rating: “warn”

Examples of incorrect code for this rule:

var React = require('react');
var React = require('react');
var Hello = <div>Hello {this.props.name}</div>;
Copy the code

Examples of correct code for this rule:

var React = require('react');
var Hello = <div>Hello {this.props.name}</div>;
var Foo = require('foo');
var Hello = <div>Hello {this.props.name}</div>;
Copy the code

Ban missing React (React/React-in-jSX-scope) in JSX

When using JSX, extends to React. CreateElement (“a”). So the React variable must be in scope. If you use the @jsx compile directive, this rule will check the specified variable instead of the React one.

'react/react-in-jsx-scope': 'error'
Copy the code
  • Rating: “error”

Examples of incorrect code for this rule:

var Hello = <div>Hello {this.props.name}</div>;
/** @jsx Foo.bar */
var React = require('react');
var Hello = <div>Hello {this.props.name}</div>;
Copy the code

Examples of correct code for this rule:

import React from "react";
var Hello = <div>Hello {this.props.name}</div>;
var React = require("react");
var Hello = <div>Hello {this.props.name}</div>;
/** @jsx Foo.bar */
var Foo = require("foo");
var Hello = <div>Hello {this.props.name}</div>;
Copy the code