Skip to content

Eslint BaseRules 翻译 & 写的一些示例

Possible Problems -- 可能的项

array-callback-return

含义:在部分数组方法的回调中必须执行 return 语句

  • Array.from
  • Array.prototype.every
  • Array.prototype.filter
  • Array.prototype.find/findLast
  • Array.prototype.findIndex/findLastIndex
  • Array.prototype.map
  • Array.prototype.reduce
  • Array.prototype.reduceRight
  • Array.prototype.some
  • Array.prototype.sort

属性:

示例:

javascript
/*eslint array-callback-return: "error"*/
arr.map((item) => {
  return item;
});

arr.some((item) => {
  return item;
});

arr.filter((item) => {
  return item;
});

arr.find((item) => {
  return item;
});

/*eslint array-callback-return: ["error", { checkForEach: false }]*/
arr.forEach((item) => {
  console.log(item);
  return item;
});

/*eslint array-callback-return: ["error", { allowImplicit: true }]*/
arr.map((item) => {
  console.log(item);
  return;
});

javascript
/*eslint array-callback-return: "error"*/

arr.map((item) => {
  console.log(item);
});

arr.map((item) => {
  console.log(item);
  return;
});

arr.some((item) => {
  console.log(item);
});

arr.filter((item) => {
  console.log(item);
});

arr.find((item) => {
  console.log(item);
});

/*eslint array-callback-return: ["error", { checkForEach: true }]*/
arr.forEach((item) => {
  console.log(item);
  return item;
});

/*eslint array-callback-return: ["error", { allowImplicit: false }]*/
arr.map((item) => {
  console.log(item);
  return;
});

constructor-super

**含义:必须****在构造函数中调用 super() - ES6 要求**

javascript
/*eslint constructor-super: "error"*/
class Person {
  constructor() {}
}
class ZhangSan extends Person {
  constructor() {
    super();
  }
}
javascript
/*eslint constructor-super: "error"*/
class Person {
  constructor() {}
}

class ZhangSan extends Person {
  constructor() {} // Expected to call 'super()'
}
// 非继承类使用super报错
class Person {
  constructor() {
    super(); // parsing error: super() call outside constructor of a subclass
  }
}

for-direction

含义:for 循环的循环方向需要正确,禁止无限 for

示例:

javascript
/*eslint for-direction: "error"*/
for (let a = 0; a < 10; a++) {}
javascript
/*eslint for-direction: "error"*/
for (let a = 0; a > 10; a++) {} // The update clause in this loop moves the variable in the direction

getter-return

含义:getters 方法必须有返回值

示例:

javascript
/*eslint getter-return: "error"*/
let person = {
  get name() {
    return "zhangSan";
  },
};

Object.defineProperty(person, "age", {
  get: function () {
    return 18;
  },
});

class PersonOne {
  get sex() {
    return "男";
  }
}
javascript
/*eslint getter-return: "error"*/
let person = {
  get name() {}, // Expexted to return a value in getter 'name'
};

Object.defineProperty(person, "age", {
  get: function () {}, // Expexted to return a value in method 'get'
});

class Person {
  get sex() {} // Expexted to return a value in getter 'sex'
}

no-async-promise-executor

含义:禁止把一个异步函数放到 promise 的执行函数中

示例:

javascript
/*eslint no-async-promise-executor: "error"*/
const foo = new Promise((resolve, reject) => {
  readFile("foo.txt", function (err, result) {
    if (err) {
      reject(err);
    } else {
      resolve(result);
    }
  });
});
const result = Promise.resolve(foo);
javascript
/*eslint no-async-promise-executor: "error"*/
const foo = new Promise(async (resolve, reject) => {
  readFile("foo.txt", function (err, result) {
    if (err) {
      reject(err);
    } else {
      resolve(result);
    }
  });
});
const result = new Promise(async (resolve, reject) => {
  resolve(await foo);
});

no-await-in-loop

含义:禁止在循环中使用 await

示例:

javascript
/*eslint no-await-in-loop: "error"*/
async function demo() {
  for (let i = 0; i < 10; i++) {
    return Promise.resolve(1);
  }
}
javascript
/*eslint no-await-in-loop: "error"*/
async function demo() {
  for (let i = 0; i < 10; i++) {
    return await Promise.resolve(1); // Unexpected 'await' inside a loop
  }
}

let a = new Promise((resolve) => {
  resolve(1);
});
async function demo() {
  for (let i = 0; i < 10; i++) {
    // return  1
    let b = await a;
    console.log(b);
  }
}

no-class-assign

含义:类不能被重新赋值

示例:

javascript
let Demo = class Demo {};
Demo = 3;

let Test = class {
  b() {
    Test = 0;
  }
};
javascript
/*eslint no-class-assign: "error"*/
class Person {
  b() {
    Person = "LiSi"; // Person is a class
  }
}

Person = "WangWu"; // Person is a class

no-compare-neg-zero

含义:不能和-0 进行比较

示例:

javascript
if (x === 0) {
}
javascript
/* eslint no-compare-neg-zero: "error" */
if (x === -0) {  // Do not use the '===' operator to compare against -0
}


if (x >= -0) {
}


if (x == -0) {
}


...

no-cond-assign

含义:禁止在条件表达式内进行赋值操作

属性:

except-parens(默认)

javascript
/*eslint no-cond-assign: ["error"]*/
let x = 1;
do {
  console.log(x);
} while ((x = 1)); // 死循环

always

示例:

javascript
/*eslint no-cond-assign: "error"*/
if ((x = 0)) {
}

do {
  console.log(x);
} while ((x = 0)); // Expected a conditional expression and instaead saw an assignment

/*eslint no-cond-assign: ["error", "always"]*/
function setHeight(a) {
  do {
    a = "100px";
  } while ((a = 1000)); // Unexpected assignment within a 'do..while' statement
}

no-const-assign

含义:禁止重新给常量赋值

示例:

javascript
let b = 0;
b = 3;
javascript
/*eslint no-const-assign: "error"*/
const a = 0;
a = 2;
a++; // 'a' is constant

no-constant-binary-expression

含义:禁止对表达式的操作不影响终值

示例:

javascript
let x = "1";
const a = x == null;
const e = (x ? x : {}) || y;
javascript
/*eslint no-constant-binary-expression: "error"*/
let x = "1";
const a = +x == null; // Unexpected constant binary expression
const e = x ? x : {} || y;
const b = x === {};

const c = x && false && y;

const d = x || true || y;

no-constant-condition

含义:禁止在条件中使用常量表达式

javascript
/*eslint no-constant-condition: ["error", { "checkLoops": false }]*/
while (true) {
  x = 1;
}
while (0) {
  x = 1;
}
for (; true; ) {
  console.log(x);
}
do {
  console.log(x);
} while (true);

示例:

javascript
/*eslint no-constant-condition: "error"*/
if (x === 1) {
  console.log(x);
}
javascript
/*eslint no-constant-condition: "error"*/
if (false) {
  // Unexpected constant condition
  console.log("test");
}
if (undefined) {
  // Unexpected constant condition
  console.log(x);
}
if (null) {
  // Unexpected constant condition
  console.log(x);
}
if ((x = 1)) {
  // Unexpected constant condition
  console.log(x);
}
if (Boolean(1)) {
  // Unexpected constant condition
  console.log(x);
}
if (x === "hello" || "bye") {
  // Unexpected constant condition
  console.log(x);
}
let result = 0 ? a : b; // Unexpected constant condition
while (true) {
  // Unexpected constant condition
  x = 1;
}
for (; true; ) {
  console.log(x);
}

no-constructor-return

含义:禁止在构造函数返回值

示例:

javascript
/*eslint no-constructor-return: "error"*/
class Person {
  constructor() {
    this.x = x;
  }
}

class Demo {
  constructor(x) {
    if (x) {
      return;
    }
  }
}
javascript
/*eslint no-constructor-return: "error"*/
class Person {
  constructor() {
    this.x = x;
    return x; // Unexpected return statement in constructor
  }
}

class Demo {
  constructor(x) {
    if (x) {
      return x; // Unexpected return statement in constructor
    }
  }
}

no-control-regex

含义:禁止在正则表达式使用控制字符

示例:

javascript
/*eslint no-control-regex: "error"*/
let pattern1 = /\x20/;
let pattern2 = /\u0020/;
let pattern3 = /\u{20}/u;
javascript
/*eslint no-control-regex: "error"*/
let demo1 = /\x1f/; // Unexpected control character(s) in regular expression: \x1f
let demo2 = new RegExp("\x1f");
let demo3 = new RegExp("\x10");

no-debugger

含义:禁止使用 debugger

示例:

javascript
function demo4(x) {
  return x;
}
javascript
/*eslint no-debugger: "error"*/
function demo4(x) {
  debugger; // Unexpected 'debuger' statement
  return x;
}

no-dupe-args

含义:在函数定义中禁止重复参数

示例:

javascript
function demo5(a, b, c) {
  console.log(a, b, c);
}
let demo6 = function (a, b, c) {
  console.log(a, b, c);
};
javascript
/*eslint no-dupe-args: "error"*/
function demo5(a, b, a) {
  // Parsing error: Argument name clash
  console.log(a, b);
}
let demo6 = function (a, b, a) {
  console.log(a, b, a);
};

no-dupe-class-members

含义:禁止出现重复类成员

示例:

javascript
/*eslint no-dupe-class-members: "error"*/
class Demo7 {
  bar() {}
  test() {}
}
class Demo8 {
  bar() {}
  get test() {
    return 1;
  }
  set test(val) {}
}
class Demo9 {
  static bar() {}
  static test() {}
}
javascript
/*eslint no-dupe-class-members: "error"*/
class Demo7 {
  bar() {}
  bar() {} // Duplicate name 'bar'
}
class Demo8 {
  bar() {}
  get bar() {} // Duplicate name 'bar'
}
class Demo9 {
  static bar() {}
  static bar() {} // Duplicate name 'bar'
}

no-dupe-else-if

含义:在 if-else-if 禁止重复条件

示例:

javascript
if (a === 1) {
  console.log(a);
} else if (a === 2) {
  console.log(b);
} else if (a === 3) {
  console.log(c);
}

if (a || b) {
  console.log(a);
} else if (c) {
  console.log(b);
}
javascript
/*eslint no-dupe-else-if: "error"*/
if (a === 1) {
  console.log(a);
} else if (a === 2) {
  console.log(b);
} else if (a === 1) {
  // This branch can never execute. Its condition is a duplicate or covered by previous conditions in the if-else-if chain
  console.log(c);
}

if (a || b) {
  console.log(a);
} else if (a) {
  // This branch can never execute. Its condition is a duplicate or covered by previous conditions in the if-else-if chain
  console.log(b);
}

no-dupe-keys

含义:禁止在对象字面量中重复键

示例:

javascript
let person = {
  a: 1,
  b: 2,
};
javascript
/*eslint no-dupe-keys: "error"*/
let person = {
  a: 1,
  a: 2, // Duplicate key 'a'
};
let demo = {
  a: 1,
  a: 1, // Duplicate key 'a'
};

no-duplicate-case

含义:禁止重复出现的 case 标签

示例:

javascript
switch (b) {
  case 1:
    break;
  case 2:
    break;
}
javascript
/*eslint no-duplicate-case: "error"*/
switch (a) {
  case 1:
    console.log(1111);
    break;
  case 2:
    console.log(22222);
    break;
  case 1: // Duplicate case label
    console.log(33333);
    break;
}

no-duplicate-imports

含义:禁止导入重复模块

属性:

javascript
/*eslint no-duplicate-imports: ["error", { "includeExports": true }]*/
import { demo1 } from "./utils";
export { demo2 } from "./utils"; // './utils' export is duplicated as import
javascript
/*eslint no-duplicate-imports: ["error", { "includeExports": true }]*/
import { demo1 } from "./utils";
export { demo1 };
export * as demo from "./utils";
export * from "./utils";

示例:

javascript
import { demo1 } from "./utils";
import * as demo from "./utils";

import { demo1 } from "./utils";
import { demo2 } from "./utils_two";
javascript
/*eslint no-duplicate-imports: "error"*/
import { demo1 } from "./utils";
import { demo2 } from "./utils"; // './utils' import is duplicated

no-empty-character-class

含义:禁止在正则表达式中使用空字符类

示例:

javascript
/*eslint no-empty-character-class: "error"*/
let reg = /^abc[a-z]/;


// 注意点
let reg2 = new RegExp("^abc[]")     原因
javascript
/*eslint no-empty-character-class: "error"*/
let reg = /^abc[]/; // Empty class

no-empty-pattern

含义:禁止空解构模式

示例:

javascript
let { a = {} } = obj;
let { b = [] } = obj;
function demo2({ a = {} }) {
  console.log(a);
}
javascript
/*eslint no-empty-pattern: "error"*/
let {} = obj; // Unexpected empty object pattern
let [] = arr;
let {
  a: {},
} = obj; // 注意此处a b只是一个占位符,实际是{} []内创建的变量
let {
  b: [],
} = obj;
function demo({}) {}

no-ex-assign

含义:禁止在 catch 子句中重新为异常赋值

示例:

javascript
try {
  console.log(11);
} catch (error) {
  let a = 1;
}
javascript
/*eslint no-ex-assign: "error"*/
try {
  console.log(11);
} catch (error) {
  error = 10; // Do not assign to the exception parameter
}

no-fallthrough

含义:禁止 case 语句的遍历

属性:

javascript
/*eslint no-fallthrough: ["error", { "commentPattern": "break[\\s\\w]*omitted" }]*/
switch (a) {
  case 1:
    console.log(a);
  // break omitted
  case 2:
    console.log(b);
}
javascript
/* eslint no-fallthrough: ["error", { "allowEmptyCase": true }] */
switch (a) {
  case 1:
  /*
   */ // 若为false,   Expected a 'break' statement before 'case'
  case 2:
    console.log(b);
}

示例:

javascript
/*eslint no-fallthrough: "error"*/
// falls through
switch (a) {
  case 1:
    console.log(a);
  // falls through
  case 2:
    console.log(b);
}

switch (a) {
  case 1:
    console.log(a);
  // fall through
  case 2:
    console.log(b);
}

switch (a) {
  case 1:
    console.log(a);
  // fallsthrough
  case 2:
    console.log(b);
}

function demo(a) {
  switch (a) {
    case 1:
      console.log(a);
      return;
    case 2:
      console.log(a);
  }
}

switch (a) {
  case 1:
    console.log(a);
    break;
  case 2:
    console.log(b);
}
javascript
/*eslint no-fallthrough: "error"*/
switch (a) {
  case 1:
    console.log(a);
  case 2:
    console.log(b); // Expected a 'break' statement before 'case'
}

no-func-assign

含义:禁止重新给函数声明赋值

示例:

javascript
let demo3 = function () {};
demo3 = 100;
javascript
/*eslint no-func-assign: "error"*/
function demo() {}
demo = 10;

let demo1 = 10;
function demo1() {}

no-import-assign

含义:禁止直接给导入的模块重新赋值,递增,递减

示例:

javascript
import { obj } from "./utils";
obj.a = 2;
javascript
/*eslint no-import-assign: "error"*/
import { demo1 } from "./utils";
import * as demo from "./utils";

demo1 = 10; // 'demo1' is read-only
demo = 200; // 'demo' is read-only

no-inner-declarations

含义:禁止在嵌套块中声明变量或函数

属性:

示例:

javascript
/*eslint no-inner-declarations: "error"*/

/*eslint no-inner-declarations: ["error", "both"]*/
var c = 4;
function demo() {}
javascript
/*eslint no-inner-declarations: "error"*/
if (a) {
  function demo() {} // Move variable declaration to program root
}

function demo1() {
  if (a == 1) {
    function demo2() {} // Move function declaration to function body root
    demo2();
  }
}

/*eslint no-inner-declarations: ["error", "both"]*/
if (a) {
  var b = 2; // Move variable declaration to program root
  console.log(b);
}

class C {
  static {
    if (c) {
      var d; // Move variable declaration to class static block body root
    }
  }
}

no-invalid-regexp

含义:禁止在 RegExp 构造函数中使用无效的正则表达式字符串

属性:

javascript
/*eslint no-invalid-regexp: ["error", { "allowConstructorFlags": ["b", "d"] }]*/
new RegExp(".", "b");

示例:

RegExp('a', 'g')

javascript
/*eslint no-invalid-regexp: "error"*/
RegExp("["); // Invalid regular expression: /[/: Unterminated character class
RegExp("\\");
RegExp(".{*}", "z"); // Invalid flags supplied to RegExp constructor 'z'
new RegExp("\\");

no-irregular-whitespace

含义:禁止使用不规则空格

javascript
\u000B - Line Tabulation (\v) - <VT>
\u000C - Form Feed (\f) - <FF>
\u00A0 - No-Break Space - <NBSP>
\u0085 - Next Line
\u1680 - Ogham Space Mark
\u180E - Mongolian Vowel Separator - <MVS>
\ufeff - Zero Width No-Break Space - <BOM>
\u2000 - En Quad
\u2001 - Em Quad
\u2002 - En Space - <ENSP>
\u2003 - Em Space - <EMSP>
\u2004 - Three-Per-Em
\u2005 - Four-Per-Em
\u2006 - Six-Per-Em
\u2007 - Figure Space
\u2008 - Punctuation Space - <PUNCSP>
\u2009 - Thin Space
\u200A - Hair Space
\u200B - Zero Width Space - <ZWSP>
\u2028 - Line Separator
\u2029 - Paragraph Separator
\u202F - Narrow No-Break Space
\u205f - Medium Mathematical Space
\u3000 - Ideographic Space

属性:

javascript
/*eslint no-irregular-whitespace: "error"*/
function demo() {
  return "<NBSP>bbb";
}

function demo1() {
  return "<ZWSP>aaa";
}

function demo3() {
  console.log("aaa<NBSP>bbb");
  return "aaa<NBSP>bbb";
}
javascript
/*eslint no-irregular-whitespace: "error"*/
function thing() /*<NBSP>*/ {
  return "test";
}
function thing(/*<NBSP>*/) {
  return "test";
}
function thing /*<NBSP>*/() {
  return "test";
}
function demo2() {
  return `template <NBSP>string`; // Trregular whitespace not allowed
}
javascript
/*eslint no-irregular-whitespace: ["error", { "skipComments": true }]*/
function demo() {
  // Description <NBSP>: some descriptive text
}
javascript
/*eslint no-irregular-whitespace: ["error", { "skipRegExps": true }]*/
function demo() {
  return / <NBSP>regexp/;
}
javascript
/*eslint no-irregular-whitespace: ["error", { "skipTemplates": true }]*/
function thing() {
  return `template <NBSP>string`;
}

no-loss-of-precision

含义:禁止出现失去精度的数字

示例:

javascript
const x = 534543535435;
const y = 0.5436567456546;
const z = 0x3233333;
javascript
/*eslint no-loss-of-precision: "error"*/
const x = 534543535435345345435345; // this number literal wiull lose precision at runtime
const y = 0.5436567456546455454;
const z = 0x323333365555555;

no-misleading-character-class

含义:不允许在字符类语法中出现由多个代码点组成的字符

``````````````````

示例:

javascript
/*eslint no-misleading-character-class: error */
/^[abc]$/
/^[👍]$/u
javascript
/*eslint no-misleading-character-class: error */
/^[Á]$/u
/^[❇️]$/u
/^[👶🏻]$/u
/^[🇯🇵]$/u
/^[👨‍👩‍👦]$/u
/^[👍]$/

no-new-native-nonconstructor

含义:禁止 new 操作符调用全局非构造函数

示例:

javascript
var num = Symbol("1");
var res = BigInt(9007199254740991);
javascript
/*eslint no-new-native-nonconstructor: "error"*/
/*eslint-env es2022*/
let num = new Symbol("1"); // 'Symbol' cannot be called as a constructor
let res = new BigInt(9007199254740991);

no-new-symbol

含义:禁止用 new 操作符操作 Symbol 对象

示例:

let num = Symbol('1')

javascript
/*eslint no-new-symbol: "error"*/
/*eslint-env es6*/

let num = new Symbol("1"); // 'Symbol' cannot be called as a constructor

no-obj-calls

含义:禁止将全局对象属性作为函数调用

示例:

javascript
let e = Math.random();
let f = JSON.stringify("str");
javascript
/*eslint no-obj-calls: "error"*/
let a = Math();
let b = new Math(); // Math is not a function
let c = JSON();
let d = new JSON();

no-promise-executor-return

含义:禁止在 promise 执行函数中 return

示例:

javascript
let a = new Promise((resolve, reject) => {
  resolve(2);
});
javascript
/*eslint no-promise-executor-return: "error"*/
// 可执行  但不对promise造成影响
let a = new Promise(() => {
  return 1; // retun value from promise executor functions cannot be read
});

no-prototype-builtins

含义:部分存在 Object 原型上的方法,禁止用对象直接调用

示例:

javascript
/*eslint no-prototype-builtins: "error"*/
var hasBarProperty = Object.prototype.hasOwnProperty.call(foo, "bar");
var isPrototypeOfBar = Object.prototype.isPrototypeOf.call(foo, bar); //判断当前对象是否为另外一个对象的原型
var barIsEnumerable = {}.propertyIsEnumerable.call(foo, "bar"); // 属性是否枚举
javascript
/*eslint no-prototype-builtins: "error"*/
var hasBarProperty = foo.hasOwnProperty("bar");
var isPrototypeOfBar = foo.isPrototypeOf(bar);
var barIsEnumerable = foo.propertyIsEnumerable("bar"); // Do not  access Object.prototype method ''' from target object'

no-self-assign

含义:禁止两边完全相同的赋值

配置:

javascript
/*eslint no-self-assign: ["error", {"props": false}]*/ // 默认是true
/*eslint no-self-assign: ["error", {"props": false}]*/
let obj = {
  a: 1,
};

obj.a = obj.a;

示例:

javascript
[1,2] = [2,1]


let a = 1
let b = 2;
[a, b] = [b, a];
javascript
1 = 1;


[1,2] = [1,2] ; // Parsing error:Assigning to rvalue

no-self-compare

含义:不允许两边完全相同的比较

示例:

javascript
/*eslint no-self-compare: "error"*/
let x = 10;
let y = 20;
if (x === y) {
  x = 20;
}
javascript
/*eslint no-self-compare: "error"*/
let x = 10;
if (x === x) {
  x = 20;
}

no-setter-return

含义:禁止在 setter 函数中 return

示例:

javascript
/*eslint no-setter-return: "error"*/
let obj = {
  set a(val) {
    this.val = val;
  },
};
javascript
/*eslint no-setter-return: "error"*/
let obj = {
  set a(val) {
    this.val = val;
    return val;
  },
};

// 类同理
Object.defineProperty(obj, "a", {
  set(value) {
    if (value < 0) {
      return false;
    }
    this.val = value;
  },
});

no-sparse-arrays

含义:禁止稀释数组

示例:

javascript
/*eslint no-sparse-arrays: "error"*/
var items = [];
var items = new Array(23);
javascript
/*eslint no-sparse-arrays: "error"*/
var items = [,];
var colors = ["red", , "blue"];

no-template-curly-in-string

含义:禁止在常规字符串中使用模版占位符语法${}

示例:

javascript
/*eslint no-template-curly-in-string: "error"*/
let demo = 2;
let b = `oh!${demo}`;
javascript
/*eslint no-template-curly-in-string: "error"*/
let a = "oh!${demo}"; // Unexpected template string expression

no-this-before-super

含义:在构造函数中调用 super()之前禁止使用 this/super

示例:

javascript
/*eslint no-this-before-super: "error"*/
class A extends B {
  constructor() {
    super();
    this.sex = "nan";
  }
}
javascript
/*eslint no-this-before-super: "error"*/
class B {
  name = "uu";
  age = 18;
}
class A extends B {
  constructor() {
    this.sex = "nan"; //  'this' is not allowed before 'super()'
    super();
  }
}

class C extends B {
  constructor() {
    super.age = 20; // 'super' is not allowed before 'super()'
    super();
  }
}

no-undef

含义:禁止使用未声明的变量,除非/_global _/注释中提到,或者配置文件中的 globals 键中指定

配置:

javascript
/*eslint no-undef: ["error", { "typeof": true }] */
if (typeof b === "string") {
} // 设置为true会检查   b is not defined

javascript
// browser

/*eslint no-undef: "error"*/
/*eslint-env browser*/
setTimeout(function () {
  alert("Hello");
});

// node

/*eslint no-undef: "error"*/
/*eslint-env node*/
var fs = require("fs");
module.exports = function () {
  console.log(fs);
};

示例:

javascript
/* global a demo*/
/*eslint no-undef: "error"*/
let result = a + 1;
let result1 = demo();
if (typeof b === "string") {
}
javascript
/*eslint no-undef: "error"*/
let result = a + 1;
let result1 = demo(); // 'demo' is not defined

no-unexpected-multiline

含义:禁止混淆多行表达式 - 合理使用; 分号

示例:

javascript
/*eslint no-unexpected-multiline: "error"*/
let b = () => {};
let a = b;
(2).toFixed();

let str = "hello";
[1, 2, 3].forEach();

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

let y = a;
/hello/g.test("hello");
javascript
/*eslint no-unexpected-multiline: "error"*/
let b = () => {};
let a = b(1 || 2); //Unexpected newline between function and ( of function call
// 方法调用意外换行
let str = "hello"[(1, 2, 3)].forEach(); //Unexpected newline between object and [ of property access
// 属性访问的对象和[之间意外换行
let x = (function () {})`hello`; // Unexpected newline between template tag and template literal

let y = a / hello / g.test("hello");

no-unmodified-loop-condition

含义:禁止在循环语句中,条件不发生更改

示例:

javascript
/*eslint no-unmodified-loop-condition: "error"*/
let a = 1;
let demo = (a) => {
  console.log(a);
};

while (a < 10) {
  demo(a);
  a++;
}

let arr = [1, 2, 3];
for (let index = 0; index < arr.length; ++index) {
  demo(arr[index]);
}
javascript
/*eslint no-unmodified-loop-condition: "error"*/
let a = 1;
let demo = (a) => {
  console.log(a);
};

while (a) {
  // a is not modified in this loop
  demo(a);
}

let arr = [1, 2, 3]; //
for (let index = 0; index < arr.length; ++a) {
  demo(arr[index]);
}

no-unreachable

含义:禁止在 return、throw、continue 和 break 语句之后出现不可访问的代码

示例:

javascript
/*eslint no-unreachable: "error"*/
let a = 1;
function demo() {
  console.log(a);
  return 1;
}

switch (a) {
  case 1:
    console.log(a);
    break;
  default:
    break;
}
javascript
/*eslint no-unreachable: "error"*/
let a = 1;
function demo() {
  return 1;
  console.log(a); // Unreachable code
}

switch (a) {
  case 1:
    console.log(a);
    break;
    console.log(a); // Unreachable code
  default:
    break;
}

no-unreachable-loop

含义:禁止出现只能循环一次的循环体

whiledo-whileforfor-infor-of

breakreturnthrow

配置:

  • "WhileStatement"while
  • "DoWhileStatement"do-while
  • "ForStatement"forfor-infor-of
  • "ForInStatement"for-in
  • "ForOfStatement"for-of
javascript
/*eslint no-unreachable-loop: ["error", { "ignore": ["ForInStatement", "ForOfStatement"] }]*/
/*eslint no-unreachable-loop: ["error", { "ignore": ["ForInStatement", "ForOfStatement"] }]*/
let obj = { a: 1, b: 2 };
for (var key in obj) {
  console.log(key);
  break;
}

示例:

javascript
/*eslint no-unreachable-loop: "error"*/
for (let i = 0; i < 5; i++) {
  console.log(11);
}

let i = 10;
while (i > 0) {
  console.log(22);
  i++;
}
javascript
/*eslint no-unreachable-loop: "error"*/
for (let i = 0; i < 5; i++) {
  console.log(11);
  break;
}

let i = 10;
while (i > 0) {
  // Invalid loop Its body allows only one interation
  console.log(22);
  i++;
  break;
}

function demo() {
  for (let index = 0; index < 5; index++) {
    if (index > 3) {
      return index;
    } else {
      throw new Error();
    }
  }
}

no-unsafe-finally

含义:禁止在 finally 块中使用控制流语句

示例:

javascript
/*eslint no-unsafe-finally: "error"*/
let demo = () => {
  console.log(1);
};
let foo = function () {
  try {
    demo();
    return 1;
  } catch (err) {
    return 2;
  } finally {
    console.log(3);
  }
};
console.log(foo());

let demo = () => {
  console.log(1);
};
let foo = function () {
  try {
    demo();
    return 1;
  } catch (err) {
    return 2;
  } finally {
    let a = () => {
      return 3;
    };
    console.log(a);
  }
};
console.log(foo());
javascript
/*eslint no-unsafe-finally: "error"*/
let demo = () => {
  console.log(1);
};
let foo = function () {
  try {
    demo();
    return 1;
  } catch (err) {
    return 2;
  } finally {
    return 3; // Unsafe usage of ReturnStatement
  }
};
console.log(foo()); // 3

let demo = () => {
  console.log(1);
};
let foo = function () {
  try {
    demo();
    return 1;
  } catch (err) {
    return 2;
  } finally {
    throw new Error(); // Unsafe usage of ReturnStatement
  }
};
console.log(foo());

no-unsafe-negation

含义:禁止对部分操作符的左边取反 in instanceof

配置:

javascript
/*eslint no-unsafe-negation: ["error", { "enforceForOrderingRelations": true }]*/
let a = 1;
let b = 2;
if (!a < b) {
  console.log(11);
}

示例:

javascript
let obj = { a: 1, b: 2 };
if (!("a" in obj)) {
}

function demo() {}
if (!(demo instanceof Function)) {
}

if (!"a" in obj) {
  console.log(3);
}
javascript
/*eslint no-unsafe-negation: "error"*/
let obj = { a: 1, b: 2 };
if (!a in obj) {
} // Unexpected negating the left operand of in operator

function demo() {}
if (!demo instanceof Function) {
}

no-unsafe-optional-chaining

含义:禁止在 undefined 的上下文中使用可选链接?.

配置:

javascript
/*eslint no-unsafe-optional-chaining: ["error", { "disallowArithmeticOperators": true }]*/
obj?.a + b; // unsafe arithmetic operation on optional chaining. It can result in NaN

obj?.a - b;

b += obj?.a;

示例:

javascript
obj?.a?.b;

obj?.a?.();

obj?.()?.a;
javascript
let obj = undefined;
(obj?.a)();    // Unsafe usage of optional chaining. If it short-circuits ..


(obj?.a).b;


[...obj?.a]


'a' in obj?.a

no-unused-private-class-members

含义:禁止出现 没有使用的私有类成员

示例:

javascript
/*eslint no-unused-private-class-members: "error"*/
class People2 {
  #age = 18;
  method() {
    return this.#age++;
  }
}
javascript
/*eslint no-unused-private-class-members: "error"*/
class People {
  #age = 18;
  #getAge() {}
}

class People2 {
  #age = 18;
  method() {
    this.#age++;
  }
}

no-unused-vars

含义:禁止使用 声明未使用的变量

配置:

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

javascript
/*eslint no-unused-vars: ["error", { "vars": "local" }]*/
/*global env*/
env = "node";

/*eslint no-unused-vars: ["error", { "varsIgnorePattern": "[Vv]arible" }]*/
let varible = 1;

javascript
/*eslint no-unused-vars: ["error", {"args": "after-used"}]*/
(function (a, b, c, d) {
    return d
})();


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

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

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

javascript
/*eslint no-unused-vars: ["error", { "destructuredArrayIgnorePattern": "^_" }]*/
const [a, _b, c] = ["a", "b", "c"];
console.log(a + c);

javascript
/*eslint no-unused-vars: ["error", { "ignoreRestSiblings": true }]*/
let data = { a: 1, b: 2, c: 3 };
let { a, ...args } = data;
let b; //  a 没使用 但是不报   因为是...args的兄弟属性
({ b, ...args } = data);

示例:

javascript
let x = 10;
alert(x);

(function (a) {
  return a;
})();
javascript
/*eslint no-unused-vars: "error"*/
/*global data */

data = 10; // data is defined

let a;

let x = 1;
x = 2;

let y = 0;
y = y + 1;

let obj = {};

obj = { a: 1 };

(function (a) {
  return 1;
})();

no-use-before-define

含义:禁止在定义变量之前使用它们

配置:

javascript
{
    "no-use-before-define": ["error", {
        "functions": true,   // 默认
        "classes": true,      // 默认
        "variables": true,    // 默认
        "allowNamedExports": false   // 默认
    }]
}

示例:

javascript
/*eslint no-use-before-define: "error"*/
let a = 1;
console.log(a);

function demo() {}
demo();

class People {
  age = 16;
}
console.log(People.age);
javascript
/*eslint no-use-before-define: "error"*/
console.log(a);
let a = 1;

demo();
function demo() {}

console.log(People.age);
class People {
  age = 16;
}

no-useless-backreference

含义:禁止在正则表达式中使用无用的反向引用

示例:

javascript
/*eslint no-useless-backreference: "error"*/
/^([a-z])\1/;
/ (?: a)(b) \1(c) /;
javascript
/*eslint no-useless-backreference: "error"*/
/^([a-z]) | \1$/;

/\1([a - z])/; // Backreference '\1' will bo ignored

/(?:a)(b)\2(c)/;

require-atomic-updates -- 需要明确

含义:<font style="color:rgb(36, 41, 47);">await</font><font style="color:rgb(36, 41, 47);">yield</font>

javascript
let result;
async function addPageNum(pageNum) {
  result += await getPageLength(pageNum);
}

Promise.all([addPageNum(1), addPageNum(2)]).then(() => {
  console.log(result); // 2   并没有出现预想的3
});

示例:

javascript
/* eslint require-atomic-updates: error */
async function addPageNum1(num) {
  result = (await getPageLength(num)) + result;
  console.log(result, 11);
}

async function addPage2(num) {
  let temp = getData(await getPageLength(num));
  result += temp;
}
javascript
/* eslint require-atomic-updates: error */
let result = 0;
function getPageLength(num) {
  return num;
}
function getData(data) {
  return data;
}

async function addPageNum2(pageNum) {
  if (!result) {
    result = await getPageLength(pageNum); // Possible race condition: 'result' might bo reassigned based on an outdated value of 'result'
  }
}

async function addPageNum(pageNum) {
  result += await getPageLength(pageNum);
}

async function addPageNum1(num) {
  result = result + getData(await getPageLength(num));
  console.log(result, 11);
}

use-isnan

含义:在检查 NaN 时要求调用 isNaN() 禁止与 NaN 进行比较

配置:

javascript
/*eslint use-isnan: ["error", {"enforceForSwitchCase": true}]*/
switch (
  NaN //   'switch(NaN)' can never match a case clause
) {
  case 1:
    console.log(1);
    break;
  default:
    break;
}

javascript
/*eslint use-isnan: ["error", {"enforceForIndexOf": true}]*/
let myArray = [NaN, 1, 2, 3];
var firstIndex = myArray.indexOf(NaN);
var lastIndex = myArray.lastIndexOf(NaN);

示例:

javascript
if (isNaN(a)) {
  console.log(a);
}

if (isNaN(b)) {
  console.log(b);
}
javascript
/*eslint use-isnan: "error"*/
let a = 1;
let b = NaN;
if (a == NaN) {
  console.log(a);
}

if (b == NaN) {
  console.log(b);
}

valid-typeof

含义:禁止 typeof 与除“undefined”、“object”、“boolean”、“number”、“string”、“function”、“symbol”和“bigint”之外的字符串比较

配置:

javascript
/*eslint valid-typeof: ["error", { "requireStringLiterals": true }]*/
typeof foo === "undefined";
typeof bar == "object";
typeof baz === "string";
typeof bar === typeof qux;

示例:

javascript
typeof "" === "string";
typeof undefined == "undefined";
typeof 1 != "number";
typeof demo !== "function";
javascript
/*eslint valid-typeof: "error"*/
typeof "" === "strnig";
typeof undefined == "undefimed";
typeof 1 != "nunber";
typeof demo !== "fucntion";

made with ❤️ by ankang