Chapter 04

lint 规则与严重级别

Biome 的 280+ 规则按 7 大维度分组——理解分组与级别,才能在"严格"与"人性化"之间找到团队的平衡点。

4.1 规则的取值

"off"
关闭——完全不跑这条规则。
"warn"
警告级——输出黄色提示,不影响退出码。CI 里 warn 不会让流水线失败。
"error"
错误级——输出红色错误,退出码非 0,CI 失败。
完整对象
少数规则支持 { "level": "error", "options": { ... } } 传选项。

4.2 7 大分组

correctness(正确性)

几乎必然是 Bug 的模式,如访问不存在变量、死代码、switch 漏掉 break。通常保持 error。

代表规则:noUnusedVariablesnoUndeclaredVariablesuseExhaustiveDependencies(React Hook 依赖)、noUnreachable

suspicious(疑似 Bug)

能编译但写法可疑,可能隐含问题——any 类型、== 松等比较、console.log 遗留、debugger

代表规则:noExplicitAnynoDoubleEqualsnoConsoleLognoDebugger

style(风格)

非 Bug 但影响一致性:const 优先、命名约定、模板字符串偏好。

代表规则:useConstuseTemplateuseSelfClosingElementsuseNamingConvention

complexity(复杂度)

简化类:箭头简写、forEachfor、冗余类型声明。

代表规则:noUselessFragmentsnoExcessiveCognitiveComplexityuseArrowFunction

performance

运行时性能:避免 delete(V8 退出 fast mode)、避免循环内创建正则。

security

安全:React dangerouslySetInnerHTMLtarget="_blank" 未带 rel="noopener"

a11y(无障碍)

针对 JSX:imgaltbutton 要可键盘触发、label 要关联控件等。

4.3 recommended 预设

"linter": {
  "rules": { "recommended": true }
}

会开启每个分组里官方推荐的约 140 条规则的默认级别(多数是 error)。可在此基础上局部调整:

"rules": {
  "recommended": true,
  "style": {
    "noNonNullAssertion": "warn",
    "useNamingConvention": {
      "level": "error",
      "options": {
        "strictCase": false,
        "conventions": [
          { "selector": { "kind": "variable" }, "formats": ["camelCase", "CONSTANT_CASE"] }
        ]
      }
    }
  }
}

4.4 常见需要调整的规则

规则默认常见团队调整
noExplicitAnyerror老项目降 warn
noConsoleLogwarn前端 error、脚本 off
noParameterAssignerror老代码迁移期 off
useExhaustiveDependencieserror保持,但单点禁用
noExcessiveCognitiveComplexityoff新项目开 warn、阈值 15
useNamingConventionwarn按团队命名约定调

4.5 代码级禁用

// biome-ignore lint/style/useTemplate: 单次格式化需要
const msg = "Hello " + name;

// 禁用整块——下一个声明之前的所有 lint
// biome-ignore-all lint/suspicious/noExplicitAny: 泛型桥接

注释格式:biome-ignore <规则类别>/<规则名>: <必须写理由>。冒号后的理由是必填——Biome 不允许匿名禁用,这是它刻意"反 ESLint 滥用"的设计。

4.6 探索规则:search 子命令

# 列出全部规则
biome explain

# 查看某条规则的说明与示例
biome explain lint/style/useConst

# 交互式搜索(IDE 中也常用)
biome lint --help

4.7 与 ESLint 规则一一对照

官方维护了一张完整对照表,常见:

ESLintBiome
no-unused-varscorrectness/noUnusedVariables
eqeqeqsuspicious/noDoubleEquals
prefer-conststyle/useConst
@typescript-eslint/no-explicit-anysuspicious/noExplicitAny
react-hooks/exhaustive-depscorrectness/useExhaustiveDependencies
jsx-a11y/alt-texta11y/useAltText
不必一次开所有规则

先 recommended + 关 3–5 条团队不适应的规则上线;跑几周再根据实际噪声调整。规则不是越多越好——团队能接受、真能修复的才有价值。

小结

Biome 的 lint 分 7 组、3 级。从 "recommended": true 起步,对需要的规则调级别或调选项,必要时用 // biome-ignore 带理由单点禁用。下一章把 format + lint + organize 合在一起的 check 命令讲清楚。