在线客服

eslint代码规范配置

adminadmin 报建百科 2024-04-25 121 22
eslint代码规范配置

要求或禁止使用分号代替 ASI (semi)

命令行中的 --fix 选项可以自动修复一些该规则报告的问题。

该规则强制使用一致的分号。

semi: ["error", "always"];
  • 等级 : "error"
  • 选项 "always": (默认) 要求在语句末尾使用分号
默认选项 "always" 的 错误 代码示例:
/*eslint semi: ["error", "always"]*/

var name = "ESLint";

object.method = function () {
  // ...
};
默认选项 "always" 的 正确 代码示例:
/*eslint semi: "error"*/

var name = "ESLint";

object.method = function () {
  // ...
};

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

此规则旨在消除未使用过的变量,方法和方法中的参数名,当发现这些存在,发出警告。 符合下面条件的变量被认为是可以使用的:

  • 作为回调函数
  • 被读取 (var y = x)
  • 传入函数中作为 argument 对象(doSomething(x))
  • 在传入到另一个函数的函数中被读取

一个变量仅仅是被赋值为 (var x = 5) 或者是被声明过,则认为它是没被考虑使用。

'no-unused-vars': [
  'warn',
  {
    args: 'none',
    ignoreRestSiblings: true,
  },
]
  • 等级 : "warn"
  • 选项 "args": none - 不检查参数
  • 选项 "ignoreRestSiblings": 选项是个布尔类型 (默认: false)。使用 Rest 属性 可能会“省略”对象中的属性,但是默认情况下,其兄弟属性被标记为 “unused”。使用该选项可以使 rest 属性的兄弟属性被忽略。
选项 { "args": "none" } 的 正确 代码示例:
/*eslint no-unused-vars: ["error", { "args": "none" }]*/

(function (foo, bar, baz) {
  return bar;
})();
选项 { "ignoreRestSiblings": true } 的 正确 代码示例:
/*eslint no-unused-vars: ["error", { "ignoreRestSiblings": true }]*/
// 'type' is ignored because it has a rest property sibling.
var { type, ...coords } = data;

禁用 console (no-console)

该规则禁止调用 console 对象的方法。

'no-console': 'off'
  • 选项 "off": 关闭禁用

强制数组方法的回调函数中有 return 语句 (array-callback-return)

该规则发现以下方法的回调函数,然后检查 return 语句的使用。

  • 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
  • 以上类型的数据。
'array-callback-return': 'off'
  • 选项 "off": 关闭禁用

要求 Switch 语句中有 Default 分支 (default-case)

此规则的目的是在 switch 语句中强制声明 default 分支。或者也可以在最后一个 case 分支下,使用 // no default 来表明此处不需要 default 分支。注释可以任何形式出现,比如 // No Default。

'default-case': ['warn', { commentPattern: '^no default$' }]
  • 等级 : "warn"
  • 选项 "commentPattern ": 设置 commentPattern 为一个正则表达式字符串,来改变默认的 /^no default$/i 注释匹配模式 此规则的目的是在 switch 语句中强制声明 default 分支。或者也可以在最后一个 case 分支下,使用 // no default 来表明此处不需要 default 分支。注释可以任何形式出现,比如 // No Default。
错误 代码示例:
/*eslint default-case: "error"*/

switch (a) {
  case 1:
    /* code */
    break;
}
正确 代码示例:
/*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
}

强制在点号之前或之后换行 (dot-location)

命令行中的 --fix 选项可以自动修复一些该规则报告的问题。

该规则旨在强制成员表达式中强制换行的一致性。防止既在点号操作之前也在之后使用换行符。

'dot-location': ['warn', 'property']
  • 等级 : "warn"
  • 选项 "property": 表达式中的点号操作符应该和属性在同一行。
选项 "property" 的 错误 代码示例:
/*eslint dot-location: ["error", "property"]*/
var foo = object.property;
选项 "property" 的 正确 代码示例:
/*eslint dot-location: ["error", "property"]*/

var foo = object.property;
var bar = object.property;

要求使用 === 和 !== (eqeqeq)

命令行中的 --fix 选项可以自动修复一些该规则报告的问题。

该规则旨在消除非类型安全的相等操作符。

eqeqeq: ["warn", "allow-null"];
  • 等级 : "warn"
  • 选项 "allow-null": 使用 “always”,然后传一个 “null” 选项,属性值为 “ignore” 代替。这将告诉 eslint 除了与 null 字面量进行比较时,总是强制使用绝对相等。

要求调用无参构造函数时带括号 (new-parens)

命令行中的 --fix 选项可以自动修复一些该规则报告的问题。

该规则目的在于,当通过 new 关键字调用构造函数时,要求使用圆括号,以此提高代码的清晰度。

'new-parens': 'warn'
  • 等级 : "warn"
错误 代码示例:
/*eslint new-parens: "error"*/

var person = new Person();
var person = new Person();
正确 代码示例:
/*eslint new-parens: "error"*/

var person = new Person();
var person = new Person();

禁止使用 Array 构造函数 (no-array-constructor)

该规则禁止使用 Array 构造函数。

'no-array-constructor': 'warn'
  • 等级 : "warn"
错误 代码示例:
/*eslint no-array-constructor: "error"*/

Array(0, 1, 2);
/*eslint no-array-constructor: "error"*/

new Array(0, 1, 2);
正确 代码示例:
/*eslint no-array-constructor: "error"*/

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

new Array(someOtherArray.length);

禁用 caller 或 callee (no-caller)

此规则目的在于阻止使用已弃用的代码和次优的代码,而且禁止使用 arguments.caller 和 arguments.callee。因此,当 arguments.caller 和 arguments.callee 被使用时,该规则将会发出警告。

'no-caller': 'warn'
  • 等级 : "warn"
错误 代码示例
/*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;
});
正确 代码示例:
/*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;
});

禁止在条件语句中出现赋值操作符(no-cond-assign)

该规则禁止在 if、for、while 和 do...while 语句中出现模棱两可的赋值操作符。

'no-cond-assign': ['warn', 'always']
  • 等级 : "warn"
  • 选项 "always": 禁止条件语句中出现赋值语句。
选项 "always" 的 错误 代码示例:
/*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);
}
选项 "always" 的 正确 代码示例:
/*eslint no-cond-assign: ["error", "always"]*/

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

不允许改变用 const 声明的变量 (no-const-assign)

该规则旨在标记修改用 const 关键字声明的变量。

'no-const-assign': 'warn'
  • 等级 : "warn"
错误 代码示例:
/*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;
正确 代码示例:
/*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);
}

禁止在正则表达式中使用控制字符(no-control-regex)

该规则禁止在正则表达式中出现控制字符。

'no-control-regex': 'warn'
  • 等级 : "warn"
错误 代码示例:
/*eslint no-control-regex: "error"*/

var pattern1 = /\x1f/;
var pattern2 = new RegExp("\x1f");
正确 代码示例:
/*eslint no-control-regex: "error"*/

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

禁止删除变量 (no-delete-var)

该规则禁止对变量使用 delete 操作符。

如果 ESLint 是在严格模式下解析代码,解析器(而不是该规则)会报告错误。

'no-delete-var': 'warn'
  • 等级 : "warn"
错误 代码示例:
/*eslint no-delete-var: "error"*/

var x;
delete x;

禁止在 function 定义中出现重复的参数 (no-dupe-args)

该规则禁止在函数定义或表达中出现重名参数。该规则并不适用于箭头函数或类方法,因为解析器会报告这样的错误。

如果 ESLint 在严格模式下解析代码,解析器(不是该规则)将报告这样的错误。

'no-dupe-args': 'warn'
  • 等级 : "warn"
错误 代码示例:
/*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);
};
正确 代码示例:
/*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);
};

不允许类成员中有重复的名称 (no-dupe-class-members)

该规则旨在标记类成员中重复名称的使用。

'no-dupe-class-members': 'warn'
  • 等级 : "warn"
错误 代码示例:
/*eslint no-dupe-class-members: "error"*/
/*eslint-env es6*/

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

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

class Foo {
  static bar() {}
  static bar() {}
}
正确 代码示例:
/*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() {}
}

禁止在对象字面量中出现重复的键 (no-dupe-keys)

该规则禁止在对象字面量中出现重复的键。

'no-dupe-keys': 'warn'
  • 等级 : "warn"
错误 代码示例:
/*eslint no-dupe-keys: "error"*/

var foo = {
  bar: "baz",
  bar: "qux",
};

var foo = {
  bar: "baz",
  bar: "qux",
};

var foo = {
  0x1: "baz",
  1: "qux",
};
正确 代码示例:
/*eslint no-dupe-keys: "error"*/

var foo = {
  bar: "baz",
  quxx: "qux",
};

禁止重复 case 标签(no-duplicate-case)

该规则禁止在 switch 语句中的 case 子句中出现重复的测试表达式。

'no-duplicate-case': 'warn'
  • 等级 : "warn"
错误 代码示例:
/*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;
}
正确 代码示例:
/*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;
}

禁止在正则表达式中出现空字符集 (no-empty-character-class)

该规则禁止在正则表达式中出现空字符集。

'no-empty-character-class': 'warn'
  • 等级 : "warn"
错误 代码示例:
/*eslint no-empty-character-class: "error"*/

/^abc[]/.test("abcdefg"); // false
"abcdefg".match(/^abc[]/); // null
正确 代码示例:
/*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"]

禁止使用空解构模式 (no-empty-pattern)

此规则目的在于标记出在解构对象和数组中的任何的空模式,每当遇到一个这样的空模式,该规则就会报告一个问题。

'no-empty-pattern': 'warn'
  • 等级 : "warn"
错误 代码示例:
/*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: [] }) {}
正确 代码示例:
/*eslint no-empty-pattern: "error"*/

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

禁用 eval()(no-eval)

此规则目的在于通过禁止使用 eval() 函数来避免潜在地危险、不必要的和运行效率低下的代码。因此,当时使用 eval() 函数时,该规则将发出警告。

'no-eval': 'warn'
  • 等级 : "warn"
错误 代码示例:
/*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");
正确 代码示例:
/*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() {}
}

禁止对 catch 子句中的异常重新赋值 (no-ex-assign)

该规则禁止对 catch 子句中的异常重新赋值。

'no-ex-assign': 'warn'
  • 等级 : "warn"
错误 代码示例:
/*eslint no-ex-assign: "error"*/

try {
  // code
} catch (e) {
  e = 10;
}
正确 代码示例:
/*eslint no-ex-assign: "error"*/

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

禁止扩展原生对象 (no-extend-native)

禁止直接修改内建对象的属性。

'no-extend-native': 'warn'
  • 等级 : "warn"
错误 代码示例:
/*eslint no-extend-native: "error"*/

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

禁止不必要的函数绑定 (no-extra-bind)

命令行中的 --fix 选项可以自动修复一些该规则报告的问题。

此规则目的在于避免不必要的 bind() 使用,并且当立即执行的函数表达式 (IIFE) 使用 bind(),但是没有一个合适的 this 值时,该规则会发出警告。此规则不会标记有函数参数绑定的 bind() 的使用情况。

注意:箭头函数不能通过使用 bind() 设置它们的自己 this 值。此规则把所有使用 bind() 的箭头函数标记为是有问题的。

'no-extra-bind': 'warn'
  • 等级 : "warn"
错误 代码示例:
/*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);
正确 代码示例:
/*eslint no-extra-bind: "error"*/

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

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

禁用不必要的标签 (no-extra-label)

命令行中的 --fix 选项可以自动修复一些该规则报告的问题。

该规则旨在消除不必要的标签。

'no-extra-label': 'warn'
  • 等级 : "warn"
错误 代码示例:
/*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;
}
正确 代码示例:
/*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;
}

禁止 case 语句落空 (no-fallthrough)

该规则旨在消除非故意 case 落空行为。因此,它会标记处没有使用注释标明的落空情况。

'no-fallthrough': 'warn'
  • 等级 : "warn"
错误 代码示例:
/*eslint no-fallthrough: "error"*/

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

  case 2:
    doSomething();
}
正确 代码示例:
/*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();
}

禁止对 function 声明重新赋值 (no-func-assign)

该规则禁止对 function 声明重新赋值。

'no-func-assign': 'warn'
  • 等级 : "warn"
错误 代码示例:
/*eslint no-func-assign: "error"*/

function foo() {}
foo = bar;

function foo() {
  foo = bar;
}
正确 代码示例:
/*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.
}

禁用隐式的 eval() (no-implied-eval)

此规则目的在于消除使用 setTimeout()、setInterval() 或 execScript() 时隐式的 eval()。因此,当它们中的任何一个使用字符串作为第一个参数时,该规则将发出警告。

'no-implied-eval': 'warn'
  • 等级 : "warn"
错误 代码示例:
/*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);
正确 代码示例:
/*eslint no-implied-eval: "error"*/

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

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

禁止在 RegExp 构造函数中出现无效的正则表达式 (no-invalid-regexp)

该规则禁止在 RegExp 构造函数中出现无效的正则表达式。

'no-invalid-regexp': 'warn'
  • 等级 : "warn"
错误 代码示例:
/*eslint no-invalid-regexp: "error"*/

RegExp("[");

RegExp(".", "z");

new RegExp("\\");
正确 代码示例:
/*eslint no-invalid-regexp: "error"*/

RegExp(".");

new RegExp();

this.RegExp("[");

禁用迭代器 (no-iterator)

此规则目的在于防止因使用 iterator属性而出现的错误,并不是所有浏览器都实现了这个属性。因此,当遇到 iterator属性时,该规则将会发出警告。

'no-iterator': 'warn'
  • 等级 : "warn"
错误 代码示例:
/*eslint no-iterator: "error"*/

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

foo.__iterator__ = function () {};

foo["__iterator__"] = function () {};
正确 代码示例:
/*eslint no-iterator: "error"*/

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

禁用与变量同名的标签 (no-label-var)

该规则旨在通过禁止使用同一作用域下的同名的变量做为标签,来创建更清晰的代码。

'no-label-var': 'warn'
  • 等级 : "warn"
错误 代码示例:
/*eslint no-label-var: "error"*/

var x = foo;
function bar() {
  x: for (;;) {
    break x;
  }
}
正确 代码示例:
/*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 (;;) {
    break q;
  }
}

禁用标签语句 (no-labels)

此规则旨在消除 JavaScript 中标签的使用。当遇到标签语句时,该规则将发出警告。

'no-labels': ['warn', { allowLoop: true, allowSwitch: false }]
  • 等级 : "warn"
  • 选项 "allowLoop": (boolean,默认是 false) - 如果这个选项被设置为 true,该规则忽略循环语句中的标签。
选项 { "allowLoop": true } 的 正确 代码示例:
/*eslint no-labels: ["error", { "allowLoop": true }]*/

label: while (true) {
  break label;
}

禁用不必要的嵌套块 (no-lone-blocks)

该规则旨在消除脚本顶部或其它块中不必要的和潜在的令人困惑的代码块。

'no-lone-blocks': 'warn'
  • 等级 : "warn"
错误 代码示例:
/*eslint no-lone-blocks: "error"*/

{
}

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

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

{
  function foo() {}
}

{
  aLabel: {
  }
}
正确 代码示例:
/*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: {
}

禁止循环中存在函数 (no-loop-func)

这个错误的出现会导致代码不能如你期望的那样运行,也表明你对 JavaScript 这门语言存在误解。 如果你不修复这个错误,你的代码可能会正常运行,带在某些情况下,可能会出现意想不到的行为。

'no-loop-func': 'warn'
  • 等级 : "warn"
错误 代码示例:
/*eslint no-loop-func: "error"*/
/*eslint-env es6*/

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

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();
}
正确 代码示例:
/*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 ...

禁止混合使用不同的操作符 (no-mixed-operators)

该规则检查 BinaryExpression 和 LogicalExpression。 该规则可能与 no-extra-parens 规则。如果你同时使用该规则和 no-extra-parens 规则,你需要使用 no-extra-parens 规则的 nestedBinaryExpressions 的选项。

'no-mixed-operators': [      'warn',      {        groups: [          ['&', '|', '^', '~', '<<', '>>', '>>>'],
          ['==', '!=', '===', '!==', '>', '>=', '<', '<='],
          ['&&', '||'],
          ['in', 'instanceof'],
        ],
        allowSamePrecedence: false,
      },
    ]
  • 等级 : "warn"
  • 选项 "groups ": (string[][]) - 指定要比较的操作符分组。 当该规则比较两个操作符时,,如果操作符在同一分组内,该规则会进行检查。否则这规则忽略它。它值是个列表组。这个组是二元操作符列表。默认为各种操作符的组。
  • 选项 "allowSamePrecedence ": (boolean) - 指定允许使用混合的两个操作符,前提是它们有同样的优先级。 默认为 true.
选项 {"groups": [["&", "|", "^", "~", "<<", ">>", ">>>"], ["&&", "||"]]} 的 错误 代码示例:
/*eslint no-mixed-operators: ["error", {"groups": [["&", "|", "^", "~", "<<", ">>", ">>>"], ["&&", "||"]]}]*/

var foo = (a && b < 0) || c > 0 || d + 1 === 0;
var foo = (a & b) | c;
选项 {"groups": [["&", "|", "^", "~", "<<", ">>", ">>>"], ["&&", "||"]]} 的 正确 代码示例:
/*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;
选项 {"allowSamePrecedence": false} 的 错误 代码示例:
/*eslint no-mixed-operators: ["error", {"allowSamePrecedence": false}]*/

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

禁止多行字符串 (no-multi-str)

该规则是为了防止多行字符串的使用。

'no-multi-str': 'warn'
  • 等级 : "warn"
错误 代码示例:
/*eslint no-multi-str: "error"*/
var x =
  "Line 1 \
         Line 2";
正确 代码示例:
/*eslint no-multi-str: "error"*/

var x = "Line 1\n" + "Line 2";

禁止重新分配本地对象(no-native-resssign)

此规则在 ESLint v3.3.0 中已弃用,并由 no-global-assign 规则取代。

这个规则不允许修改只读的全局变量。 ESLint 能够将全局变量配置为只读。

  • 指定环境
  • 指定全局
'no-native-reassign': 'warn'
  • 等级 : "warn"
错误 代码示例:
/*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;
正确 代码示例:
/*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;

不允许在 in 表达式中否定左操作数(no-negated-in-lhs)

这个规则在 ESLint v3.3.0 中被弃用,并被 no-unsafe-negation 取代。

该规则不允许否定 in 表达式中的左操作数。

'no-negated-in-lhs': 'warn'
  • 等级 : "warn"
错误 代码示例:
/*eslint no-negated-in-lhs: "error"*/

if (!key in object) {
  // operator precedence makes it equivalent to (!key) in object
  // and type conversion makes it equivalent to (key ? "false" : "true") in object
}
正确 代码示例:
/*eslint no-negated-in-lhs: "error"*/

if (!(key in 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
}

禁用 Function 构造函数 (no-new-func)

该规则会高亮标记出不好的实践的使用。把一个字符串传给 Function 构造函数,你需要引擎解析该字符串,这一点同调用 eval 函数一样。

'no-new-func': 'warn'
  • 等级 : "warn"
错误 代码示例:
/*eslint no-new-func: "error"*/

var x = new Function("a", "b", "return a + b");
var x = Function("a", "b", "return a + b");
正确 代码示例:
/*eslint no-new-func: "error"*/

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

禁止使用 Object 构造函数 (no-new-object)

该规则禁止使用 Object 构造函数。。

'no-new-object': 'warn'
  • 等级 : "warn"
错误 代码示例:
/*eslint no-new-object: "error"*/

var myObject = new Object();

var myObject = new Object();
正确 代码示例:
/*eslint no-new-object: "error"*/

var myObject = new CustomObject();

var myObject = {};

禁止使用 Symbol 构造函数 (no-new-symbol)

这个规则是为了防止 Symbol 与 new 操作员的意外调用。

'no-new-symbol': 'warn'
  • 等级 : "warn"
错误 代码示例:
/*eslint no-new-symbol: "error"*/
/*eslint-env es6*/

var foo = new Symbol("foo");
正确 代码示例:
/*eslint no-new-symbol: "error"*/
/*eslint-env es6*/

var foo = Symbol("foo");

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

禁止原始包装实例 (no-new-wrappers)

此规则目的在于消除通过 new 操作符使用 String、Number 和 Boolean 。因此,每当遇到 new String、new Number 或者 new Boolean,该规则都会发出警告。

'no-new-wrappers': 'warn'
  • 等级 : "warn"
错误 代码示例:
/*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();
var numberObject = new Number();
var booleanObject = new Boolean();
正确 代码示例:
/*eslint no-new-wrappers: "error"*/

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

var object = new MyString();

禁止将全局对象当作函数进行调用 (no-obj-calls)

该规则禁止将 Math、JSON 和 Reflect 对象当作函数进行调用。

'no-obj-calls': 'warn'
  • 等级 : "warn"
错误 代码示例:
/*eslint no-obj-calls: "error"*/

var math = Math();
var json = JSON();
var reflect = Reflect();
正确 代码示例:
/*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");

禁用八进制字面量 (no-octal)

'no-octal': 'warn'
  • 等级 : "warn"
错误 代码示例:
/*eslint no-octal: "error"*/

var num = 071;
var result = 5 + 07;
正确 代码示例:
/*eslint no-octal: "error"*/

var num = "071";

禁止在字符串字面量中使用八进制转义序列 (no-octal-escape)

该规则禁止在字符串字面量中使用八进制转义序列。 如果 ESLint 是在严格模式下解析代码,解析器(而不是该规则)会报告错误。

'no-octal-escape': 'warn'
  • 等级 : "warn"
错误 代码示例:
/*eslint no-octal-escape: "error"*/

var foo = "Copyright \251";
正确 代码示例:
/*eslint no-octal-escape: "error"*/

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

var foo = "Copyright \xA9"; // hexadecimal

禁止重新声明变量 (no-redeclare)

此规则目旨在消除同一作用域中多次声明同一变量。

'no-redeclare': 'warn'
  • 等级 : "warn"
错误 代码示例:
/*eslint no-redeclare: "error"*/

var a = 3;
var a = 10;
正确 代码示例:
/*eslint no-redeclare: "error"*/

var a = 3;
// ...
a = 10;

禁止正则表达式字面量中出现多个空格 (no-regex-spaces)

该规则禁止在正则表达式字面量中出现多个空格。

'no-regex-spaces': 'warn'
  • 等级 : "warn"
错误 代码示例:
/*eslint no-regex-spaces: "error"*/

var re = /foo   bar/;
var re = new RegExp("foo   bar");
正确 代码示例:
/*eslint no-regex-spaces: "error"*/

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

禁止使用特定的语法 (no-restricted-syntax)

该规则禁止使用特定的(由用户来指定)语法。

'no-restricted-syntax': ['warn', 'WithStatement']
  • 等级 : "warn"
  • 选项 "WithStatement": 禁用 with
选项对话"FunctionExpression", "WithStatement", BinaryExpression[operator='in']的错误代码示例:
/* eslint no-restricted-syntax: ["error", "FunctionExpression", "WithStatement", "BinaryExpression[operator='in']"] */

with (me) {
  dontMess();
}

var doSomething = function () {};

foo in bar;
选项对话"FunctionExpression", "WithStatement"的正确代码示例:
/* eslint no-restricted-syntax: ["error", "FunctionExpression", "WithStatement", "BinaryExpression[operator='in']"] */

me.dontMess();

function doSomething() {}

foo instanceof bar;

禁用 Script URL (no-script-url)

'no-script-url': 'warn'
  • 等级 : "warn"
错误 代码示例:
/*eslint no-script-url: "error"*/

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

禁止自身赋值 (no-self-assign)

该规则旨在消除自身赋值的情况。

'no-self-assign': 'warn'
  • 等级 : "warn"
错误 代码示例:
/*eslint no-self-assign: "error"*/

foo = foo;

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

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

({ a, b } = { a, x });
正确 代码示例:
/*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];

禁止自身比较(no-self-compare)

该规则为了突出一个潜在的令人困惑的、无意义的代码。几乎没有场景需要你比较变量本身。

'no-self-compare': 'warn'
  • 等级 : "warn"
错误 代码示例:
/*eslint no-self-compare: "error"*/

var x = 10;
if (x === x) {
  x = 20;
}

不允许使用逗号操作符 (no-sequences)

此规则禁止逗号操作符的使用,以下情况除外:

  • 在初始化或者更新部分 for 语句时。
  • 如果表达式序列被明确包裹在括号中。
'no-sequences': 'warn'
  • 等级 : "warn"
错误 代码示例:
/*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)) {
}
正确 代码示例:
/*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)) {}

关键字不能被遮蔽 (no-shadow-restricted-names)

'no-shadow-restricted-names': 'warn'
  • 等级 : "warn"
错误 代码示例:
/*eslint no-shadow-restricted-names: "error"*/

function NaN() {}

!function (Infinity) {};

var undefined;

try {
} catch (eval) {}
正确 代码示例:
/*eslint no-shadow-restricted-names: "error"*/

var Object;

function f(a, b) {}

禁用稀疏数组 (no-sparse-arrays)

该规则禁止使用稀疏数组,也就是逗号之前没有任何元素的数组。该规则不适用于紧随最后一个元素的拖尾逗号的情况。

'no-sparse-arrays': 'warn'
  • 等级 : "warn"
错误 代码示例:
/*eslint no-sparse-arrays: "error"*/

var items = [,];
var colors = ["red", , "blue"];
正确 代码示例:
/*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"];

不允许在常规字符串中使用模板字面量占位符语法 (no-template-curly-in-string)

这个规则的目的是警告当一个常规字符串包含了一个模板字面上的占位符。它将在发现包含模板文字的位置符(%20{something}),它使用“或”引用引号。

'no-template-curly-in-string':%20'warn'
  • 等级%20:%20"warn"
错误%20代码示例:
/*eslint%20no-template-curly-in-string:%20"error"*/
"Hello%20${name}!";
"Hello%20${name}!";
"Time:%20${12%20*%2060%20*%2060%20*%201000}";
正确%20代码示例:
/*eslint%20no-template-curly-in-string:%20"error"*/
`Hello%20${name}!`;
`Time:%20${12%20*%2060%20*%2060%20*%201000}`;

templateFunction`Hello%20${name}`;
在构造函数中禁止在调用%20super()之前使用%20this%20或%20super。%20(no-this-before-super)

该规则旨在标记出在调用%20super()%20之前使用%20this%20或%20super%20的情况。

'no-this-before-super':%20'warn'
  • 等级%20:%20"warn"
错误%20代码示例:
/*eslint%20no-this-before-super:%20"error"*/
/*eslint-env%20es6*/

class%20A%20extends%20B%20{
%20%20constructor()%20{
%20%20%20%20this.a%20=%200;
%20%20%20%20super();
%20%20}
}

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

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

class%20A%20extends%20B%20{
%20%20constructor()%20{
%20%20%20%20super(this.foo());
%20%20}
}
正确%20代码示例:
/*eslint%20no-this-before-super:%20"error"*/
/*eslint-env%20es6*/

class%20A%20{
%20%20constructor()%20{
%20%20%20%20this.a%20=%200;%20//%20OK,%20this%20class%20doesn't%20have%20an%20`extends`%20clause.
%20%20}
}

class%20A%20extends%20B%20{
%20%20constructor()%20{
%20%20%20%20super();
%20%20%20%20this.a%20=%200;%20//%20OK,%20this%20is%20after%20`super()`.
%20%20}
}

class%20A%20extends%20B%20{
%20%20foo()%20{
%20%20%20%20this.a%20=%200;%20//%20OK.%20this%20is%20not%20in%20a%20constructor.
%20%20}
}
限制可以被抛出的异常%20(no-throw-literal)

此规则目的在于保持异常抛出的一致性,通过禁止抛出字面量和那些不可能是%20Error%20对象的表达式。

'no-throw-literal':%20'warn'
  • 等级%20:%20"warn"
错误%20代码示例:
/*eslint%20no-throw-literal:%20"error"*/
/*eslint-env%20es6*/

throw%20"error";

throw%200;

throw%20undefined;

throw%20null;

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

var%20err%20=%20new%20Error();
throw%20`${err}`;
正确%20代码示例:
/*eslint%20no-throw-literal:%20"error"*/

throw%20new%20Error();

throw%20new%20Error("error");

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

try%20{
%20%20throw%20new%20Error("error");
}%20catch%20(e)%20{
%20%20throw%20e;
}
禁用未声明的变量%20(no-undef)

对任何未声明的变量的引用都会引起一个警告,除非显式地在%20/global%20.../%20注释中指定。

'no-undef':%20'error'
  • 等级%20:%20"error"
错误%20代码示例:
/*eslint%20no-undef:%20"error"*/

var%20a%20=%20someFunction();
b%20=%2010;
有%20global%20声明时,该规则的%20正确%20代码示例:
//*global%20someFunction%20b:true*/
/*eslint%20no-undef:%20"error"*/

var%20a%20=%20someFunction();
b%20=%2010;
有%20global%20声明时,该规则的%20错误%20代码示例:
/*global%20b*/
/*eslint%20no-undef:%20"error"*/

b%20=%2010;
禁用特定的全局变量%20(no-restricted-globals)

该规则允许你指定你不想在你的应用中使用的全局变量的名称。

'no-restricted-globals':%20['error'].concat(restrictedGlobals)
  • 等级%20:%20"error"
  • 选项%20"restrictedGlobals":%20全局变量
全局变量%20"event",%20"fdescribe"%20的%20错误%20代码示例:
/*global%20event,%20fdescribe*/
/*eslint%20no-restricted-globals:%20["error",%20"event",%20"fdescribe"]*/

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

fdescribe("foo",%20function%20()%20{});
全局变量%20"event"%20的%20正确%20代码示例:
/*global%20event*/
/*eslint%20no-restricted-globals:%20["error",%20"event"]*/

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

var%20event%20=%201;
禁止使用令人困惑的多行表达式%20(no-unexpected-multiline)

该规则禁止使用令人困惑的多行表达式。

'no-unexpected-multiline':%20'warn'
  • 等级%20:%20"warn"
错误%20代码示例:
/*eslint%20no-unexpected-multiline:%20"error"*/

var%20foo%20=%20bar(1%20||%202).baz();

var%20hello%20=%20"world"[(1,%202,%203)].forEach(addNumber);

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

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

let%20x%20=%20foo%20/%20regex%20/%20g.test(bar);
正确%20代码示例:
var%20foo%20=%20bar;
(1%20||%202).baz();

var%20foo%20=%20bar;
(1%20||%202).baz();

var%20hello%20=%20"world";
[1,%202,%203].forEach(addNumber);

var%20hello%20=%20"world";
void%20[1,%202,%203].forEach(addNumber);

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

let%20tag%20=%20function%20()%20{};
tag`hello`;
禁止使用令人困惑的多行表达式%20(no-unexpected-multiline)

该规则禁止在%20return、throw、continue%20和%20break%20语句后出现不可达代码。

'no-unexpected-multiline':%20'warn'
  • 等级%20:%20"warn"
错误%20代码示例:
/*eslint%20no-unreachable:%20"error"*/

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

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

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

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

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

for%20(;;)%20{}
console.log("done");
正确%20代码示例:
/*eslint%20no-unreachable:%20"error"*/

function%20foo()%20{
%20%20return%20bar();
%20%20function%20bar()%20{
%20%20%20%20return%201;
%20%20}
}

function%20bar()%20{
%20%20return%20x;
%20%20var%20x;
}

switch%20(foo)%20{
%20%20case%201:
%20%20%20%20break;
%20%20%20%20var%20x;
}
禁止未使用过的表达式%20(no-unused-expressions)

此规则的目的在于消除未使用过的表达式,它们在程序中不起任何作用。 该规则不适用于使用%20new%20操作符的函数或构造函数调用,因为它们可能会有副作用

'no-unused-expressions':%20[
%20%20'warn',
%20%20{
%20%20%20%20allowShortCircuit:%20true,
%20%20%20%20allowTernary:%20true,
%20%20%20%20allowTaggedTemplates:%20true,
%20%20},
]
  • 等级%20:%20"warn"
  • 选项%20"allowShortCircuit":%20设置为%20true%20将允许你在表达式中使用逻辑短路求值。(默认为%20false)
  • 选项%20"allowTernary":%20设置为%20true%20将允许你在表达式中使用类似逻辑短路求值的三元运算符。(默认为%20false)。
  • 选项%20"allowTaggedTemplates":%20设置为%20true%20将允许你在表达式中使用带标签的模板字面量%20(默认:%20false)。
选项%20{%20"allowShortCircuit":%20true%20}%20的%20错误%20代码示例:
/*eslint%20no-unused-expressions:%20["error",%20{%20"allowShortCircuit":%20true%20}]*/

a%20||%20b;
选项%20{%20"allowShortCircuit":%20true%20}%20的%20正确%20代码示例:
/*eslint%20no-unused-expressions:%20["error",%20{%20"allowShortCircuit":%20true%20}]*/

a%20&&%20b();
a()%20||%20(b%20=%20c);
选项%20{%20"allowTernary":%20true%20}%20的%20错误%20代码示例:
/*eslint%20no-unused-expressions:%20["error",%20{%20"allowTernary":%20true%20}]*/

a%20?%20b%20:%200;
a%20?%20b%20:%20c();
选项%20{%20"allowTernary":%20true%20}%20的%20正确%20代码示例:
/*eslint%20no-unused-expressions:%20["error",%20{%20"allowTernary":%20true%20}]*/

a%20?%20b()%20:%20c();
a%20?%20(b%20=%20c)%20:%20d();
选项%20{%20"allowTaggedTemplates":%20true%20}%20的%20错误%20代码示例:
/*eslint%20no-unused-expressions:%20["error",%20{%20"allowTaggedTemplates":%20true%20}]*/

`some%20untagged%20template%20string`;
选项%20{%20"allowTaggedTemplates":%20true%20}%20的%20正确%20代码示例:
/*eslint%20no-unused-expressions:%20["error",%20{%20"allowTaggedTemplates":%20true%20}]*/

tag`some%20tagged%20template%20string`;
禁用未使用过的标签%20(no-unused-labels)

命令行中的%20--fix%20选项可以自动修复一些该规则报告的问题。

该规则旨在消除未使用过的标签。

'no-unused-labels':%20'warn'
  • 等级%20:%20"warn"
错误%20代码示例:
/*eslint%20no-unused-labels:%20"error"*/

A:%20var%20foo%20=%200;

B:%20{
%20%20foo();
}

C:%20for%20(let%20i%20=%200;%20i%20<%2010;%20++i)%20{
%20%20foo();
}
正确%20代码示例:
/*eslint%20no-unused-labels:%20"error"*/

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

B:%20for%20(let%20i%20=%200;%20i%20<%2010;%20++i)%20{
%20%20if%20(foo())%20{
%20%20%20%20break%20B;
%20%20}
%20%20bar();
}
禁止定义前使用%20(no-use-before-define)

当使用一个还未声明的标示符是会报警告。

'no-use-before-define':%20[
%20%20'warn',
%20%20{
%20%20%20%20functions:%20false,
%20%20%20%20classes:%20false,
%20%20%20%20variables:%20false,
%20%20},
]
  • 等级%20:%20"warn"
  • 选项%20"functions":%20这个参数表示该规则是否要检测函数的声明。%20如果参数是%20true,该规则会在引用一个未提前声明的函数时发出警报。%20否则,忽略这些引用。因为函数声明作用域会被提升,所以这样做是安全的。%20参数默认值是%20true。
  • 选项%20"classes":%20这个参数表示是否要检测上层作用域中的类声明。%20如果参数是%20true,该规则会在引用一个未提前声明的类时发出警报。%20否则,该规则会忽略对上层作用域中的类声明的引用。%20因为类声明作用域不会被提升,所以这样做可能是危险的。%20参数默认是%20true。
  • 选项%20"variables":%20这个参数表示是否要在上层作用域内检测变量声明。%20如果参数是%20true,该规则会在引用一个未提前声明的变量时发出警报。%20否则,该规则会忽略在上层作用域中变量声明的引用,然而仍然会报告对同一作用域中的变量声明的引用。%20参数默认是%20true。
选项{%20"functions":%20false%20}的%20正确%20代码示例:
/*eslint%20no-use-before-define:%20["error",%20{%20"functions":%20false%20}]*/

f();
function%20f()%20{}
选项{%20"classes":%20false%20}的%20错误%20代码示例:
/*eslint%20no-use-before-define:%20["error",%20{%20"classes":%20false%20}]*/
/*eslint-env%20es6*/

new%20A();
class%20A%20{}
选项{%20"classes":%20false%20}的%20正确%20代码示例:
/*eslint%20no-use-before-define:%20["error",%20{%20"classes":%20false%20}]*/
/*eslint-env%20es6*/

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

class%20A%20{}
选项%20{%20"variables":%20false%20}%20的%20错误%20代码示例:
/*eslint%20no-use-before-define:%20["error",%20{%20"variables":%20false%20}]*/

console.log(foo);
var%20foo%20=%201;
选项%20{%20"variables":%20false%20}%20的%20正确%20代码示例:
/*eslint%20no-use-before-define:%20["error",%20{%20"variables":%20false%20}]*/

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

var%20foo%20=%201;
不允许在对象上使用不必要的计算属性键(no-useless-computed-key)

命令行中的%20--fix%20选项可以自动修复一些该规则报告的问题。

此规则不允许对计算属性键进行不必要的使用。

'no-useless-computed-key':%20'warn'
  • 等级%20:%20"warn"
错误%20代码示例:
/*eslint-env%20es6*/

var%20a%20=%20{%20["0"]:%200%20};
var%20a%20=%20{%20["0+1,234"]:%200%20};
var%20a%20=%20{%20[0]:%200%20};
var%20a%20=%20{%20["x"]:%200%20};
var%20a%20=%20{%20["x"]()%20{}%20};
正确%20代码示例:
/*eslint%20no-useless-computed-key:%20"error"*/

var%20c%20=%20{%20a:%200%20};
var%20c%20=%20{%200:%200%20};
var%20a%20=%20{%20x()%20{}%20};
var%20c%20=%20{%20a:%200%20};
var%20c%20=%20{%20"0+1,234":%200%20};
禁止没有必要的字符拼接%20(no-useless-concat)

此规则目的在于标记可以组合成单个字面量的两个字面量的拼接。字面量可以是字符串或者模板字面量。

'no-useless-concat':%20'warn'
  • 等级%20:%20"warn"
错误%20代码示例:
/*eslint%20no-useless-concat:%20"error"*/
/*eslint-env%20es6*/

//%20these%20are%20the%20same%20as%20"10"
var%20a%20=%20`some`%20+%20`string`;
var%20a%20=%20"1"%20+%20"0";
var%20a%20=%20"1"%20+%20`0`;
var%20a%20=%20`1`%20+%20"0";
var%20a%20=%20`1`%20+%20`0`;
正确%20代码示例:
/*eslint%20no-useless-concat:%20"error"*/

//%20when%20a%20non%20string%20is%20included
var%20c%20=%20a%20+%20b;
var%20c%20=%20"1"%20+%20a;
var%20a%20=%201%20+%20"1";
var%20c%20=%201%20-%202;
//%20when%20the%20string%20concatenation%20is%20multiline
var%20c%20=%20"foo"%20+%20"bar";
禁用不必要的构造函数%20(no-useless-constructor)

该规则标记可以被安全移除但又不改变类的行为的构造函数。

'no-useless-constructor':%20'warn'
  • 等级%20:%20"warn"
错误%20代码示例:
/*eslint%20no-useless-constructor:%20"error"*/
/*eslint-env%20es6*/

class%20A%20{
%20%20constructor()%20{}
}

class%20A%20extends%20B%20{
%20%20constructor(...args)%20{
%20%20%20%20super(...args);
%20%20}
}
正确%20代码示例:
/*eslint%20no-useless-constructor:%20"error"*/

class%20A%20{}

class%20A%20{
%20%20constructor()%20{
%20%20%20%20doSomething();
%20%20}
}

class%20A%20extends%20B%20{
%20%20constructor()%20{
%20%20%20%20super("foo");
%20%20}
}

class%20A%20extends%20B%20{
%20%20constructor()%20{
%20%20%20%20super();
%20%20%20%20doSomething();
%20%20}
}
禁用不必要的转义%20(no-useless-escape)

该规则标记在不改变代码行为的情况下可以安全移除的转义。

'no-useless-escape':%20'warn'
  • 等级%20:%20"warn"
错误%20代码示例:
/*eslint%20no-useless-escape:%20"error"*/

"\'";
'\"';
"\#";
"\e";
`\"`;
`\"${foo}\"`;
`\#{foo}`;
/\!/;
/\@/;
正确%20代码示例:
/*eslint%20no-useless-escape:%20"error"*/

"\"";
'\'';
"\x12";
"\u00a9";
"\371";
"xs\u2111";
`\``;
`\${${foo}\}`;
`$\{${foo}\}`;
/\\/g;
/\t/g;
/\w\$\*\^\./;
禁止将%20import,%20export%20和%20destructured%20assignments%20重命名为相同的名称(no-useless-rename)

此规则不允许将%20import,%20export%20和%20destructured%20assignments%20重命名为相同的名称。

'no-useless-rename':%20[
%20%20'warn',
%20%20{
%20%20%20%20ignoreDestructuring:%20false,
%20%20%20%20ignoreImport:%20false,
%20%20%20%20ignoreExport:%20false,
%20%20},
]
  • 等级%20:%20"warn"
  • 选项%20"ignoreDestructuring":%20设置为时%20false,此规则检查解构分配(默认)
  • 选项%20"ignoreImport":%20设置为此时%20false,此规则检查导入(默认)
  • 选项%20"ignoreExport":%20设置为此时%20false,此规则检查导出(默认)
默认情况下此规则的代码不正确的示例:
/*eslint%20no-useless-rename:%20"error"*/

import%20{%20foo%20}%20from%20"bar";
export%20{%20foo%20};
export%20{%20foo%20}%20from%20"bar";
let%20{%20foo:%20foo%20}%20=%20bar;
let%20{%20foo:%20foo%20}%20=%20bar;
function%20foo({%20bar:%20bar%20})%20{}
({%20foo:%20foo%20})%20=>%20{};
默认情况下此规则的正确代码示例:
/*eslint%20no-useless-rename:%20"error"*/

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

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

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

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

({%20foo%20})%20=>%20{};
({%20foo:%20bar%20})%20=>%20{};
禁用%20with%20语句%20(no-with)

此规则目的在于排除%20with%20语句。

如果%20ESLint%20在严格模式下解析代码,解析器(不是该规则)将报告这样的错误。

'no-with':%20'warn'
  • 等级%20:%20"warn"
错误%20代码示例:
/*eslint%20no-with:%20"error"*/

with%20(point)%20{
%20%20r%20=%20Math.sqrt(x%20*%20x%20+%20y%20*%20y);%20//%20is%20r%20a%20member%20of%20point?
}
正确%20代码示例:
/*eslint%20no-with:%20"error"*/
/*eslint-env%20es6*/

const%20r%20=%20({%20x,%20y%20})%20=>%20Math.sqrt(x%20*%20x%20+%20y%20*%20y);
禁止属性前有空白%20(no-whitespace-before-property)

命令行中的%20--fix%20选项可以自动修复一些该规则报告的问题。

该规则禁止在点号周围或对象属性之前的左括号前出现空白。如果对象和属性不在同一行上,这种情况,该规则允许使用空白,因为对级联的属性增加新行是一种很普遍的行为。

'no-whitespace-before-property':%20'warn'
  • 等级%20:%20"warn"
错误%20代码示例:
/*eslint%20no-whitespace-before-property:%20"error"*/

foo[bar];

foo.bar;

foo.bar;

foo.bar.baz;

foo.bar().baz();

foo.bar().baz();
正确%20代码示例:
/*eslint%20no-whitespace-before-property:%20"error"*/

foo.bar;

foo[bar];

foo[bar];

foo.bar.baz;

foo.bar().baz();

foo.bar().baz();

foo.bar().baz();
要求必须有基数%20(radix)

该规则旨在防止出现不确定的字符串对数字的转换或防止在现代环境中出现多余的基数%2010。

'radix':%20'warn'
  • 等级%20:%20"warn"
错误%20代码示例:
/*eslint%20radix:%20"error"*/

var%20num%20=%20parseInt("071");

var%20num%20=%20parseInt(someValue);

var%20num%20=%20parseInt("071",%20"abc");

var%20num%20=%20parseInt();
正确%20代码示例:
/*eslint%20radix:%20"error"*/

var%20num%20=%20parseInt("071",%2010);

var%20num%20=%20parseInt("071",%208);

var%20num%20=%20parseFloat(someValue);
禁用函数内没有%20yield%20的%20generator%20函数(require-yield)

如果%20generator%20函数内部没有%20yield%20关键字,该规则将发出警告。

'radix':%20'warn'
  • 等级%20:%20"warn"
错误%20代码示例:
/*eslint%20require-yield:%20"error"*/
/*eslint-env%20es6*/

function*%20foo()%20{
%20%20return%2010;
}
正确%20代码示例:
/*eslint%20require-yield:%20"error"*/
/*eslint-env%20es6*/

function*%20foo()%20{
%20%20yield%205;
%20%20return%2010;
}

function%20foo()%20{
%20%20return%2010;
}

//%20This%20rule%20does%20not%20warn%20on%20empty%20generator%20functions.
function*%20foo()%20{}
强制限制扩展运算符及其表达式之间的空格(rest-spread-spacing)

命令行中的%20--fix%20选项可以自动修复一些该规则报告的问题。

这条规则的目的是强制限制扩展运算符及其表达式之间的空格。该规则还支持当前的对象在启用时扩展属性。

'rest-spread-spacing':%20['warn',%20'never']
  • 等级%20:%20"warn"
  • 选项%20"never":%20(默认)扩展运算符及其表达式之间不允许有空格。
此规则的错误代码示例"never":
/*eslint%20rest-spread-spacing:%20["error",%20"never"]*/

fn(...%20args)
[...%20arr,%204,%205,%206]
let%20[a,%20b,%20...%20arr]%20=%20[1,%202,%203,%204,%205];
function%20fn(...%20args)%20{%20console.log(args);%20}
let%20{%20x,%20y,%20...%20z%20}%20=%20{%20x:%201,%20y:%202,%20a:%203,%20b:%204%20};
let%20n%20=%20{%20x,%20y,%20...%20z%20};
此规则的正确代码示例"never":
/*eslint%20rest-spread-spacing:%20["error",%20"never"]*/

fn(...args)
[...arr,%204,%205,%206]
let%20[a,%20b,%20...arr]%20=%20[1,%202,%203,%204,%205];
function%20fn(...args)%20{%20console.log(args);%20}
let%20{%20x,%20y,%20...z%20}%20=%20{%20x:%201,%20y:%202,%20a:%203,%20b:%204%20};
let%20n%20=%20{%20x,%20y,%20...z%20};
要求或禁止使用严格模式指令%20(strict)

命令行中的%20--fix%20选项可以自动修复一些该规则报告的问题。

该规则要求或禁止严格模式指令。

strict:%20["warn",%20"never"];
  • 等级%20:%20"warn"
  • 选项%20"never":%20禁用严格模式指令
选项%20"never"%20的%20错误%20代码示例:
/*eslint%20strict:%20["error",%20"never"]*/

"use%20strict";

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

function%20foo()%20{
%20%20"use%20strict";
}
选项%20"never"%20的%20正确%20代码示例:
/*eslint%20strict:%20["error",%20"never"]*/

function%20foo()%20{}
要求或禁止使用%20Unicode%20字节顺序标记%20(BOM)%20(unicode-bom)

命令行中的%20--fix%20选项可以自动修复一些该规则报告的问题。

如果使用了%20"always"%20选项,该规则要求文件始终以%20Unicode%20BOM%20字符%20U+FEFF%20开头。如果是%20"never",文件决不能以%20U+FEFF%20开始。

'unicode-bom':%20['warn',%20'never']
  • 等级%20:%20"warn"
  • 选项%20"never":%20(默认)%20文件不能以%20Unicode%20BOM%20开头
选项%20"never"%20的%20错误%20代码示例:
/*eslint%20unicode-bom:%20["error",%20"never"]*/

U%20+%20FEFF;
var%20abc;
选项%20"never"%20的%20正确%20代码示例:
/*eslint%20unicode-bom:%20["error",%20"never"]*/

var%20abc;
要求调用%20isNaN()检查%20NaN%20(use-isnan)

该规则禁止与%20‘NaN’%20的比较。

'use-isnan':%20'warn'
  • 等级%20:%20"warn"
错误%20代码示例:
/*eslint%20use-isnan:%20"error"*/

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

if%20(foo%20!=%20NaN)%20{
%20%20//%20...
}
正确%20代码示例:
/*eslint%20use-isnan:%20"error"*/

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

if%20(!isNaN(foo))%20{
%20%20//%20...
}
强制%20typeof%20表达式与有效的字符串进行比较%20(valid-typeof)

该规则强制%20typeof%20表达式与有效的字符串进行比较。

'valid-typeof':%20'warn'
  • 等级%20:%20"warn"
错误%20代码示例:
/*eslint%20valid-typeof:%20"error"*/

typeof%20foo%20===%20"strnig";
typeof%20foo%20==%20"undefimed";
typeof%20bar%20!=%20"nunber";
typeof%20bar%20!==%20"fucntion";
正确%20代码示例:
/*eslint%20valid-typeof:%20"error"*/

typeof%20foo%20===%20"string";
typeof%20bar%20==%20"undefined";
typeof%20foo%20===%20baz;
typeof%20bar%20===%20typeof%20qux;
禁止某些对象属性%20(no-restricted-properties)

此规则查找访问给定对象名称上的给定属性键,无论是在读取属性的值还是将其作为函数调用时。您可以指定一个可选消息来指示替代%20API%20或限制原因。

'no-restricted-properties':%20[
%20%20'error',
%20%20{
%20%20%20%20object:%20'System',
%20%20%20%20property:%20'import',
%20%20%20%20message:%20'Please%20use%20import()%20instead.',
%20%20},
]
  • 等级%20:%20"error"
  • 选项%20"object":%20不允许的类名
  • 选项%20"property":%20不允许的属性名
  • 选项%20"message":%20提示信息
import/first

该规则报告任何在非导入语句之后的导入。

'import/first':%20'error'
  • 等级%20:%20"error"
错误%20代码示例:
import%20foo%20from%20"./foo";

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

import%20bar%20from%20"./bar";%20//%20<-%20reported
正确%20代码示例:
import%20foo%20from%20"./foo";
import%20bar%20from%20"./bar";

//%20some%20module-level%20initializer
initWith(foo);
import/no-amd

在模块范围的报告%20require([array],%20...)和%20define([array],%20...)函数调用。如果参数!=%202%20不会警告,或者第一个参数不是一个字符串数组。

'import/no-amd':%20'error'
  • 等级%20:%20"error"
错误%20代码示例:
define([%20“%20a%20”,“%20b%20”%20],函数(a,b){%20/%20*%20...%20*%20/%20})

require([%20“%20b%20”,“%20c%20”%20],函数(b,c){%20/%20*%20...%20*%20/%20})
import/no-webpack-loader-syntax

禁止在导入中使用%20Webpack%20加载器语法

'import/no-webpack-loader-syntax':%20'error'
  • 等级%20:%20"error"
错误%20代码示例:
import%20myModule%20from%20"my-loader!my-module";
import%20theme%20from%20"style!css!./theme.css";

var%20myModule%20=%20require("my-loader!./my-module");
var%20theme%20=%20require("style!css!./theme.css");
正确%20代码示例:
import%20myModule%20from%20"my-module";
import%20theme%20from%20"./theme.css";

var%20myModule%20=%20require("my-module");
var%20theme%20=%20require("./theme.css");
防止将注释作为文本节点插入(react/jsx-no-comment-textnodes)

这个规则防止注释字符串(例如,以//或开始/*)被意外注入为%20JSX%20语句中的文本节点。

'react/jsx-no-comment-textnodes':%20'warn'
  • 等级%20:%20"warn"
错误%20代码示例:
var%20Hello%20=%20createReactClass({
%20%20render:%20function%20()%20{
%20%20%20%20return%20<div>//%20empty%20div</div>;
%20%20},
});

var%20Hello%20=%20createReactClass({
%20%20render:%20function%20()%20{
%20%20%20%20return%20<div>/*%20empty%20div%20*/</div>;
%20%20},
});
正确%20代码示例:
var%20Hello%20=%20createReactClass({
%20%20displayName:%20'Hello',
%20%20render:%20function()%20{
%20%20%20%20return%20<div>{/*%20empty%20div%20*/}</div>;
%20%20}
});

var%20Hello%20=%20createReactClass({
%20%20displayName:%20'Hello',
%20%20render:%20function()%20{
%20%20%20%20return%20<div%20/*%20empty%20div%20*/></div>;
%20%20}
});

var%20Hello%20=%20createReactClass({
%20%20displayName:%20'Hello',
%20%20render:%20function()%20{
%20%20%20%20return%20<div%20className={'foo'%20/*%20temp%20class%20*/}</div>;
%20%20}
});
禁止%20JSX%20中的重复属性(react/jsx-no-duplicate-props)

使用重复的%20props%20创建%20JSX%20元素可能会导致应用程序出现意外的行为。

'react/jsx-no-duplicate-props':%20['warn',%20{%20ignoreCase:%20true%20}]
  • 等级%20:%20"warn"
  • 选项%20"ignoreCase":%20忽略大小写。默认为%20false。
错误%20代码示例:
<%20Hello%20%20name%20=%20“%20John%20”%20%20name%20=%20“%20John%20”%20/>;
正确%20代码示例:
<%20Hello%20%20firstname%20=%20“%20John%20”%20%20lastname%20=%20“%20Doe%20”%20/>;
禁止使用不安全%20target='_blank'(react/jsx-no-target-blank)

禁止使用不安全%20target='_blank'%20(外链)

'react/jsx-no-target-blank':%20'warn'
  • 等级%20:%20"warn"
错误%20代码示例:
var%20Hello%20=%20<a%20target="_blank"%20href="http://example.com/"></a>;
正确%20代码示例:
var%20Hello%20=%20<p%20target="_blank"></p>;
var%20Hello%20=%20(
%20%20<a%20target="_blank"%20rel="noopener%20noreferrer"%20href="http://example.com"></a>
);
var%20Hello%20=%20<a%20target="_blank"%20href="relative/path/in/the/host"></a>;
var%20Hello%20=%20<a%20target="_blank"%20href="/absolute/path/in/the/host"></a>;
var%20Hello%20=%20<a></a>;
在%20JSX%20中禁止未声明的变量(react/jsx-no-undef)

在%20JSX%20中禁止未声明的变量

'react/jsx-no-undef':%20'error'
  • 等级%20:%20"error"
错误%20代码示例:
<Hello%20name="John"%20/>;
//%20will%20ignore%20Text%20in%20the%20global%20scope%20and%20warn
var%20Hello%20=%20React.createClass({
%20%20render:%20function%20()%20{
%20%20%20%20return%20<Text>Hello</Text>;
%20%20},
});
module.exports%20=%20Hello;
正确%20代码示例:
var%20Hello%20=%20require("./Hello");

<Hello%20name="John"%20/>;
锚点-的-内容(jsx-a11y/anchor-has-content)

强制锚具有内容,屏幕阅读器可以访问内容。可访问性意味着它不会使用%20aria-hidden%20道具隐藏。

'jsx-a11y/anchor-has-content':%20'warn'
  • 等级%20:%20"warn"
错误%20代码示例:
<a%20/>
<a><TextWrapper%20aria-hidden%20/></a>
正确%20代码示例:
<a>Anchor%20Content!</a>
<a><TextWrapper%20/><a>
<a%20dangerouslySetInnerHTML={{%20__html:%20'foo'%20}}%20/>
aria-activedescendant-的%20TabIndex(jsx-a11y/aria-activedescendant-has-tabindex)

aria-activedescendant%20用于管理复合小部件中的焦点。具有该属性的元素%20aria-activedescendant%20保留活动文档焦点;%20它通过将该元素的%20ID%20分配给值来指示它的哪个子元素具有次要焦点%20aria-activedescendant。这个模式用于构建一个像搜索类型的选择列表。搜索输入框保留文档焦点,以便用户可以键入输入。如果按下向下箭头键并突出显示搜索建议,则建议元素的%20ID%20将作为%20aria-activedescendant%20输入元素的值应用。

由于一个元素%20aria-activedescendant%20必须是可放大的,它必须有一个固有%20tabIndex%20的零或者%20tabIndex%20用%20tabIndex%20属性声明一个零。

'jsx-a11y/aria-activedescendant-has-tabindex':%20'warn'
  • 等级%20:%20"warn"
错误%20代码示例:
<div%20aria-activedescendant={someID}%20/>
<div%20aria-activedescendant={someID}%20tabIndex={-1}%20/>
<div%20aria-activedescendant={someID}%20tabIndex="-1"%20/>
<input%20aria-activedescendant={someID}%20tabIndex={-1}%20/>
正确%20代码示例:
<CustomComponent%20/>
<CustomComponent%20aria-activedescendant={someID}%20/>
<CustomComponent%20aria-activedescendant={someID}%20tabIndex={0}%20/>
<CustomComponent%20aria-activedescendant={someID}%20tabIndex={-1}%20/>
<div%20/>
<input%20/>
<div%20tabIndex={0}%20/>
<div%20aria-activedescendant={someID}%20tabIndex={0}%20/>
<div%20aria-activedescendant={someID}%20tabIndex="0"%20/>
<div%20aria-activedescendant={someID}%20tabIndex={1}%20/>
<input%20aria-activedescendant={someID}%20/>
<input%20aria-activedescendant={someID}%20tabIndex={0}%20/>
元素不能使用无效的%20aria%20属性(jsx-a11y/aria-props)

元素不能使用无效的%20aria%20属性。如果找到%20WAI-ARIA%20状态和属性规范中%20aria-*没有列出的属性,将会失败。

'jsx-a11y/aria-props':%20'warn'
  • 等级%20:%20"warn"
错误%20代码示例:
<!--%20Bad:%20Labeled%20using%20incorrectly%20spelled%20aria-labeledby%20-->
<div%20id="address_label">Enter%20your%20address</div>
<input%20aria-labeledby="address_label">
正确%20代码示例:
<!--%20Good:%20Labeled%20using%20correctly%20spelled%20aria-labelledby%20-->
<div%20id="address_label">Enter%20your%20address</div>
<input%20aria-labelledby="address_label">
aria%20状态和属性值必须有效(jsx-a11y/aria-proptypes)

aria%20状态和属性值必须有效

'jsx-a11y/aria-proptypes':%20'warn'
  • 等级%20:%20"warn"
错误%20代码示例:
<!--%20Bad:%20the%20aria-hidden%20state%20is%20of%20type%20true/false%20-->
<span%20aria-hidden="yes">foo</span>
正确%20代码示例:
<!--%20Good:%20the%20aria-hidden%20state%20is%20of%20type%20true/false%20-->
<span%20aria-hidden="true">foo</span>
元素必须使用有效的%20aria%20角色(jsx-a11y/aria-role)(#jsx-a11y/aria-props)

具有%20aria%20角色的元素必须使用有效的,非抽象的%20aria%20角色。

'jsx-a11y/aria-role':%20'warn'
  • 等级%20:%20"warn"
错误%20代码示例:
<div%20role="datepicker"></div>%20<!--%20Bad:%20"datepicker"%20is%20not%20an%20ARIA%20role%20-->
<div%20role="range"></div>%20%20%20%20%20%20<!--%20Bad:%20"range"%20is%20an%20_abstract_%20ARIA%20role%20-->
<div%20role=""></div>%20%20%20%20%20%20%20%20%20%20%20<!--%20Bad:%20An%20empty%20ARIA%20role%20is%20not%20allowed%20-->
<Foo%20role={role}></Foo>%20%20%20%20%20%20%20<!--%20Bad:%20ignoreNonDOM%20is%20set%20to%20false%20or%20not%20set%20-->
正确%20代码示例:
<div%20role="button"></div>%20%20%20%20%20<!--%20Good:%20"button"%20is%20a%20valid%20ARIA%20role%20-->
<div%20role={role}></div>%20%20%20%20%20%20%20<!--%20Good:%20role%20is%20a%20variable%20&%20cannot%20be%20determined%20until%20runtime.%20-->
<div></div>%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20<!--%20Good:%20No%20ARIA%20role%20-->
<Foo%20role={role}></Foo>%20%20%20%20%20%20%20<!--%20Good:%20ignoreNonDOM%20is%20set%20to%20true%20-->
aria%20不受支持的元素(jsx-a11y/aria-unsupported-elements)

某些保留的%20DOM%20元素不支持%20aria%20角色,状态和属性。这往往是因为他们是不可见的,例如%20meta,html,script,style。此规则强制这些%20DOM%20元素不包含%20role%20和/或%20aria-*%20props。

'jsx-a11y/aria-unsupported-elements':%20'warn'
  • 等级%20:%20"warn"
错误%20代码示例:
<!--%20Bad:%20the%20meta%20element%20should%20not%20be%20given%20any%20ARIA%20attributes%20-->
<meta%20charset="UTF-8"%20aria-hidden="false"%20/>
正确%20代码示例:
<!--%20Good:%20the%20meta%20element%20should%20not%20be%20given%20any%20ARIA%20attributes%20-->
<meta%20charset="UTF-8"%20/>
标题要有内容(jsx-a11y/heading-has-content)

强制执行标题元素(h1,h2%20等)为内容和内容的屏幕读取器访问。可访问性意味着它不会使用%20aria-hidden%20prop%20隐藏。

'jsx-a11y/heading-has-content':%20'warn'
  • 等级%20:%20"warn"
错误%20代码示例:
<h1%20/>
<h1><TextWrapper%20aria-hidden%20/>
正确%20代码示例:
<h1>Heading%20Content!</h1>
<h1><TextWrapper%20/><h1>
<h1%20dangerouslySetInnerHTML={{%20__html:%20'foo'%20}}%20/>

#######

iframe%20的标题(jsx-a11y/iframe-has-title)

<iframe>%20元素必须具有唯一的标题属性以向用户指示其内容。

'jsx-a11y/iframe-has-title':%20'warn'
  • 等级%20:%20"warn"
错误%20代码示例:
<iframe%20/>
<iframe%20{...props}%20/>
<iframe%20title=""%20/>
<iframe%20title={''}%20/>
<iframe%20title={``}%20/>
<iframe%20title={undefined}%20/>
<iframe%20title={false}%20/>
<iframe%20title={true}%20/>
<iframe%20title={42}%20/>
正确%20代码示例:
<iframe%20title="This%20is%20a%20unique%20title"%20/>
<iframe%20title={uniqueTitle}%20/>
img-多余的-alt(jsx-a11y/img-redundant-alt)

强制%20img%20alt%20属性不包含单词图像,图片或照片。屏幕阅读器已经将%20img%20元素宣布为图片。不需要使用图像,照片和/或图片等文字。

'jsx-a11y/img-redundant-alt':%20'warn'
  • 等级%20:%20"warn"
错误%20代码示例:
<img%20src="foo"%20alt="Photo%20of%20foo%20being%20weird."%20/>
<img%20src="bar"%20alt="Image%20of%20me%20at%20a%20bar!"%20/>
<img%20src="baz"%20alt="Picture%20of%20baz%20fixing%20a%20bug."%20/>
正确%20代码示例:
<img%20src="foo"%20alt="Foo%20eating%20a%20sandwich."%20/>
<img%20src="bar"%20aria-hidden%20alt="Picture%20of%20me%20taking%20a%20photo%20of%20an%20image"%20/>%20//%20Will%20pass%20because%20it%20is%20hidden.
<img%20src="baz"%20alt={`Baz%20taking%20a%20${photo}`}%20/>%20//%20This%20is%20valid%20since%20photo%20is%20a%20variable%20name.
href%20必须是有效性的(jsx-a11y/href-no-hash)

a链接具有有效%20href%20属性的%20HTML%20元素被正式定义为表示超链接。也就是说,一个%20HTML%20文档与另一个%20HTML%20文档之间的链接,或者%20HTML%20文档中的一个位置与同一文档内的另一个位置之间的链接。

'jsx-a11y/href-no-hash':%20'warn'
  • 等级%20:%20"warn"
错误%20代码示例:
/*Anchors%20should%20be%20a%20button:*/
<a%20onClick={foo}%20/>
<a%20href="#"%20onClick={foo}%20/>
<a%20href={"#"}%20onClick={foo}%20/>
<a%20href={`#`}%20onClick={foo}%20/>
<a%20href="javascript:void(0)"%20onClick={foo}%20/>
<a%20href={"javascript:void(0)"}%20onClick={foo}%20/>
<a%20href={`javascript:void(0)`}%20onClick={foo}%20/>

/*Missing%20href%20attribute:*/
<a%20/>
<a%20href={undefined}%20/>
<a%20href={null}%20/>

/*Invalid%20href%20attribute:*/
<a%20href="#"%20/>
<a%20href={"#"}%20/>
<a%20href={`#`}%20/>
<a%20href="javascript:void(0)"%20/>
<a%20href={"javascript:void(0)"}%20/>
<a%20href={`javascript:void(0)`}%20/>
正确%20代码示例:
<a%20href="https://github.com"%20/>
<a%20href="#section"%20/>
<a%20href="foo"%20/>
<a%20href="/foo/bar"%20/>
<a%20href={someValidPath}%20/>
<a%20href="https://github.com"%20onClick={foo}%20/>
<a%20href="#section"%20onClick={foo}%20/>
<a%20href="foo"%20onClick={foo}%20/>
<a%20href="/foo/bar"%20onClick={foo}%20/>
<a%20href={someValidPath}%20onClick={foo}%20/>

#######

禁止%20access-key(jsx-a11y/no-access-key)

强制元素没有%20accessKey%20prop。访问键是允许%20Web%20开发人员将键盘快捷键分配给元素的%20HTML%20属性。屏幕阅读器和键盘所使用的键盘快捷键和键盘命令之间的不一致会造成无障碍复杂性,因此为避免复杂化,不应使用快捷键。

'jsx-a11y/no-access-key':%20'warn'
  • 等级%20:%20"warn"
错误%20代码示例:
<div%20accessKey="h"%20/>
正确%20代码示例:
<div%20/>
禁用废弃的元素(jsx-a11y/no-distracting-elements)

这些元素很可能被弃用,应该避免。默认情况下,下列元素在视觉上分散注意力:<marquee>和<blink>

'jsx-a11y/no-distracting-elements':%20'warn'
  • 等级%20:%20"warn"
错误%20代码示例:
<marquee%20/>
<blink%20/>
正确%20代码示例:
<div%20/>
禁用多余的%20roles(jsx-a11y/no-redundant-roles)

一些%20HTML%20元素具有由浏览器实现的本地语义。这包括默认/隐含的%20ARIA%20角色。设置匹配其默认/隐含角色的%20ARIA%20角色是多余的,因为它已经被浏览器设置。

'jsx-a11y/no-redundant-roles':%20'warn'
  • 等级%20:%20"warn"
错误%20代码示例:
<button%20role="button"%20/>
<img%20role="img"%20src="foo.jpg" />
正确 代码示例:
<div />
<button role="presentation" />
<MyComponent role="main" />

role 有要求的 aria props(jsx-a11y/role-has-required-aria-props)

具有 aria role 的元素必须具有该角色的所有必需属性。

'jsx-a11y/role-has-required-aria-props': 'warn'
  • 等级 : "warn"
错误 代码示例:
<!-- Bad: the checkbox role requires the aria-checked state -->
<span role="checkbox" aria-labelledby="foo" tabindex="0"></span>
正确 代码示例:
<!-- Good: the checkbox role requires the aria-checked state -->
<span role="checkbox" aria-checked="false" aria-labelledby="foo" tabindex="0"></span>

role-支持的-aria-props(jsx-a11y/role-supports-aria-props)

强制定义显式或隐式角色的元素仅包含 aria-*由其支持的属性 role。许多 ARIA 属性(状态和属性)只能用于具有特定角色的元素。一些元素具有隐含的角色,例如<a href="#" />,将解析为 role="link"。

'jsx-a11y/role-supports-aria-props': 'warn'
  • 等级 : "warn"
错误 代码示例:
<!-- 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>
正确 代码示例:
<!-- 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>

范围(jsx-a11y/scope)

scope 的范围应该只在< th >元素上使用。

'jsx-a11y/scope': 'warn'
  • 等级 : "warn"
错误 代码示例:
<div scope />
正确 代码示例:
<th scope="col" />
<th scope={scope} />

禁止 isMounted 的使用(react/no-is-mounted)

isMounted 是一种反模式,在使用 ES6 类时是不可用的,并且正在被官方弃用。

'react/no-is-mounted': 'warn'
  • 等级 : "warn"
错误 代码示例:
var Hello = createReactClass({
  handleClick: function () {
    setTimeout(function () {
      if (this.isMounted()) {
        return;
      }
    });
  },
  render: function () {
    return <div onClick={this.handleClick.bind(this)}>Hello</div>;
  },
});
正确 代码示例:
var Hello = createReactClass({
  render: function () {
    return <div onClick={this.props.handleClick}>Hello</div>;
  },
});

强制 ES5 或 ES6 类在渲染函数中返回值(react/require-render-return)

render 在组件中编写方法时,很容易忘记返回 JSX 内容。如果 return 声明丢失,此规则将会发出警告。

'react/require-render-return': 'error'
  • 等级 : "error"
错误 代码示例:
var Hello = createReactClass({
  render() {
    <div>Hello</div>;
  },
});

class Hello extends React.Component {
  render() {
    <div>Hello</div>;
  }
}
正确 代码示例:
var Hello = createReactClass({
  render() {
    return <div>Hello</div>;
  },
});

class Hello extends React.Component {
  render() {
    return <div>Hello</div>;
  }
}

样式属性值强制作为对象(react/style-prop-object)

要求 prop 的值 style 是一个对象或是一个对象的变量。

'react/style-prop-object': 'warn'
  • 等级 : "warn"
错误 代码示例:
<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 });
正确 代码示例:
<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 });

访问-表情符号(jsx-a11y/accessible-emoji)

表情符号已经成为向最终用户传达内容的常用方式。然而,对于使用屏幕阅读器的人来说,他/她可能根本不知道这个内容在那里。通过在屏幕阅读器中包装表情符号,给予 role="img"和提供有用的描述 aria-label,屏幕阅读器将表情符号视为可访问树中的图像,并为最终用户提供可访问的名称。

'jsx-a11y/accessible-emoji': 'warn'
  • 等级 : "warn"
错误 代码示例:
<span role="img" aria-label="Snowman">&#9731;</span>
<span role="img" aria-label="Panda">          
          				
代办报建

本公司承接江浙沪报建代办施工许可证。
联系人:张经理,18321657689(微信同号)。

喜欢0发布评论

22条评论

  • 游客 发表于 2个月前

    很有看点!https://sdceda.com/lao/411200023/

  • 8001直播 发表于 2个月前

    这篇文章真是让人受益匪浅!http://lxvxj.usab1visa.com

  • 游客 发表于 1个月前

    大神就是大神,这么经典!http://www.jiagu1.com/fei/br0q12aeg/

  • 游客 发表于 1个月前

    太高深了,理解力不够用了!http://www.jiagu1.com/fei/z7jfynapv/

  • 游客 发表于 1个月前

    这个帖子好无聊啊!http://www.jiagu1.com/fei/ou1xd0v3h/

  • 万彩软件 发表于 4周前

    视死如归的架势啊!http://rlu38n.rqxxpt.com

  • 原来的万彩吧版本 发表于 3周前

    世界末日我都挺过去了,看到楼主我才知道为什么上帝留我到现在!http://izm.haianjsw.com

  • 3d558开奖前后关系 发表于 2周前

    世界末日我都挺过去了,看到楼主我才知道为什么上帝留我到现在!http://r2c272.momei365.com

  • 游客 发表于 1周前

    顶一个!http://bqai1.xaqrpj.com.cn

发表评论

  • 昵称(必填)
  • 邮箱
  • 网址