Skip to content
← Back to rules

eslint/id-length 风格

它做了什么

此规则通过计算给定标识符的字素数量,强制执行最小和/或最大标识符长度约定。

为什么这是不好的?

ex\_t 这样的极短标识符名称,或者像 hashGeneratorResultOutputContainerObject 这样的极长标识符名称,会使代码更难阅读,并可能降低可维护性。为防止这种情况,可以强制执行最小和/或最大标识符长度。

示例

此规则的 错误 代码示例:

js
/* id-length: "error" */ // 默认值为最小长度 2 字符 ({ "min": 2 })

const x = 5;
obj.e = document.body;
const foo = function (e) {};
try {
  dangerousStuff();
} catch (e) {
  // 忽略,因为很多人都是这么做的
}
const myObj = { a: 1 };
(a) => {
  a * a;
};
class y {}
class Foo {
  x() {}
}
class Bar {
  #x() {}
}
class Baz {
  x = 1;
}
class Qux {
  #x = 1;
}
function bar(...x) {}
function baz([x]) {}
const [z] = arr;
const {
  prop: [i],
} = {};
function qux({ x }) {}
const { j } = {};
const { prop: a } = {};
({ prop: obj.x } = {});

此规则的 正确 代码示例:

js
/* id-length: "error" */ // 默认值为最小长度 2 字符 ({ "min": 2 })

const num = 5;
function _f() {
  return 42;
}
function _func() {
  return 42;
}
obj.el = document.body;
const foo = function (evt) {
  /* 执行操作 */
};
try {
  dangerousStuff();
} catch (error) {
  // 忽略,因为很多人都是这么做的
}
const myObj = { apple: 1 };
(num) => {
  num * num;
};
function bar(num = 0) {}
class MyClass {}
class Foo {
  method() {}
}
class Bar {
  #method() {}
}
class Baz {
  field = 1;
}
class Qux {
  #field = 1;
}
function baz(...args) {}
function qux([longName]) {}
const { prop } = {};
const {
  prop: [name],
} = {};
const [longName] = arr;
function foobar({ prop }) {}
function foobaz({ a: prop }) {}
const { a: property } = {};
({ prop: obj.longName } = {});
const data = { x: 1 }; // 因为使用了引号而被豁免
data["y"] = 3; // 因为是计算属性访问而被豁免

配置

此规则接受一个配置对象,包含以下属性:

exceptionPatterns

type: string[]

用于排除规则检查的标识符正则表达式模式数组。 例如,["^x.*"] 将排除所有以 "x" 开头的标识符。

exceptions

type: string[]

default: []

被排除在规则之外的标识符名称数组。 例如,["x", "y", "z"] 将允许单字母标识符 "x"、"y" 和 "z"。

max

type: integer

default: 18446744073709551615

标识符中允许的最大字素数量。 默认值为无上限(实际上无限)。

min

type: integer

default: 2

标识符中所需的最小字素数量。

properties

type: "always" | "never"

default: "always"

当设置为 "never" 时,不会检查属性名的长度。 当设置为 "always"(默认值)时,属性名的检查方式与其他标识符相同。

如何使用

要通过配置文件或 CLI 启用 此规则,可以使用:

json
{
  "rules": {
    "id-length": "error"
  }
}
bash
oxlint --deny id-length

参考资料