mcpField
B
biome

biome

github.com/tenequm测试与质量4052 次安装6 天前更新
代码仓库

关于 biome

biome 是面向 JavaScript、TypeScript 等项目的代码检查、格式化和导入整理技能资料。它介绍 Biome 2.4 配置、类型感知规则及自定义规则,适合维护代码质量工具链的开发者。

主要功能

  1. 01统一运行格式化、检查与导入整理
  2. 02配置文件范围与排除规则
  3. 03类型感知 lint 规则
  4. 04GritQL 自定义规则
  5. 05CI 与编辑器集成

适用场景

  1. 01为项目配置 Biome 检查和格式化
  2. 02在 CI 中验证代码规范
  3. 03根据类型信息检测未处理的 Promise
  4. 04为项目编写自定义 lint 规则

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/tenequm/skills --skill biome

安装后在 Claude Code 中输入/biome确认已加载。

包含的文件

除 SKILL.md 外,安装时一起下载的参考资料和脚本。

CHANGELOG.md
LICENSE.txt
references/
rules-reference.md

详细介绍

Biome

为 JavaScript、TypeScript、JSX、CSS 和 GraphQL 提供快速、统一的 lint、格式化和导入组织功能。Biome 2.4 无需 TypeScript 编译器即可进行类型感知 lint,支持用于自定义规则的 GritQL 插件,以及基于领域的规则分组。单个二进制文件,默认零配置,兼容 97% 的 Prettier。

关键规则

files.ignore 不存在——请使用带否定模式的 files.includes

Biome 2.x 仅支持 files.includes(带 s)。files.ignore、files.include(不带 s)和 files.exclude 均不存在。使用其中任何一个都会触发 Found an unknown key 错误。

files 下唯一有效的键是:includes、maxSize、ignoreUnknown。(experimentalScannerIgnores 仍然存在,但上游文档现已将其标记为已弃用,并且可能会移除。)

若要排除文件(生成的代码、供应商文件等),请在 files.includes 中使用否定模式:

{
  "files": {
    "includes": ["**", "!**/routeTree.gen.ts", "!**/generated/**"]
  }
}

若要让扫描器跳过某些路径,即使其他工具或辅助功能原本会处理这些路径,也请在 files.includes 中使用 !! 强制忽略语法(替代 experimentalScannerIgnores):

{
  "files": {
    "includes": ["**", "!!**/legacy-vendor/**"]
  }
}

不要使用 overrides 和 linter/formatter/assists: { enabled: false } 来跳过生成的文件——这种方式很脆弱(容易漏掉 assists/import organizer 之类的子系统),而且不必要地复杂。只需通过 files.includes 排除即可。

始终使用 biome check,不要分开运行 lint 和格式化

biome check 会一次性运行格式化工具、linter 和导入组织器。在 CI 中,切勿分别调用 biome lint 和 biome format——请使用 biome check(CI 模式下使用 biome ci)。

biome.json 位于项目根目录

每个项目都需要在根目录放置一个 biome.json。单体仓库中的软件包使用嵌套配置,并通过 "extends": "//" 继承根配置。切勿使用 "extends": ["../../biome.json"] 这类相对路径。

使用 --write 应用修复
biome check --write .            # Apply safe fixes only
biome check --write --unsafe .   # Apply all fixes including unsafe (review changes)

biome lint 和 biome format 支持将 --fix 作为 --write 的别名,但 biome check 才是规范的入口命令,且文档指定的标志是 --write。请使用 --write。

安全与不安全的修复。 移除未使用的导入、参数和变量被归类为不安全(外部调用方仍可能引用该符号)。普通的 --write 会保留这些内容并报告诊断。请使用 --write --unsafe(并检查差异),或手动删除。

固定精确版本,并在升级后迁移
pnpm add --save-dev --save-exact @biomejs/biome@latest
pnpm biome migrate --write

biome.json 中的 $schema URL 会固定版本(例如 "$schema": "https://biomejs.dev/schemas/2.4.13/schema.json")。升级 @biomejs/biome 后,在运行 biome migrate --write 之前,CLI 会报错 The configuration schema version does not match the CLI version。请在升级过程中运行迁移,而不是之后再运行。

快速开始

pnpm add --save-dev --save-exact @biomejs/biome
pnpm biome init    # Creates default biome.json with recommended rules
IDE 设置

VS Code——安装 biomejs.biome 扩展:

{
  "editor.defaultFormatter": "biomejs.biome",
  "editor.formatOnSave": true,
  "editor.codeActionsOnSave": {
    "source.fixAll.biome": "explicit",
    "source.organizeImports.biome": "explicit"
  }
}

source.fixAll.biome 会在保存时应用安全的 lint 修复;source.organizeImports.biome 会运行辅助功能。要与 CLI 的 biome check --write 保持一致,两者都需要启用。

Zed——原生提供 Biome 扩展。内联配置功能(v2.4)允许编辑器覆盖规则,而不影响 biome.json。注意拼写:Zed 使用 inline_config(snake_case);VS Code 扩展使用 inlineConfig(camelCase)。

{
  "formatter": { "language_server": { "name": "biome" } },
  "lsp": {
    "biome": {
      "settings": {
        "inline_config": {
          "linter": { "rules": { "suspicious": { "noConsole": "off" } } }
        }
      }
    }
  }
}
CI 集成
pnpm biome ci .                                  # No writes, non-zero exit on errors
pnpm biome ci --reporter=default --reporter=github .  # GitHub Actions annotations

配置(biome.json)

React/TypeScript 项目的推荐配置
{
  "$schema": "./node_modules/@biomejs/biome/configuration_schema.json",
  "vcs": {
    "enabled": true,
    "clientKind": "git",
    "useIgnoreFile": true
  },
  "files": {
    "includes": [
      "src/**/*.ts", "src/**/*.tsx",
      "tests/**/*.ts", "**/*.config.ts", "**/*.json",
      "!**/generated", "!**/components/ui"
    ]
  },
  "formatter": {
    "enabled": true,
    "indentStyle": "space",
    "indentWidth": 2,
    "lineWidth": 120
  },
  "linter": {
    "enabled": true,
    "rules": { "recommended": true },
    "domains": { "react": "recommended" }
  },
  "javascript": {
    "formatter": { "quoteStyle": "double" }
  },
  "assist": {
    "enabled": true,
    "actions": {
      "source": { "organizeImports": "on" }
    }
  }
}
格式化选项

关键选项:indentStyle("space"/"tab")、indentWidth、lineWidth、lineEnding("lf"/"crlf")、trailingNewline。JavaScript 专用选项:quoteStyle、trailingCommas、semicolons、arrowParentheses、bracketSpacing。

Linter 规则配置

规则支持 "error"、"warn"、"info" 或 "off" 严重级别。部分规则接受选项:

{
  "linter": {
    "rules": {
      "recommended": true,
      "style": {
        "noRestrictedGlobals": {
          "level": "error",
          "options": {
            "deniedGlobals": {
              "Buffer": "Use Uint8Array for browser compatibility."
            }
          }
        },
        "useComponentExportOnlyModules": "off"
      }
    }
  }
}
导入整理器

导入整理器(Biome Assist)会合并重复项、按距离排序,并支持自定义分组。从 v2.4.13 起,它还会对 TypeScript 模块(module "x" { ... })和 .d.ts 声明文件中的导入进行排序。

{
  "assist": {
    "enabled": true,
    "actions": {
      "source": {
        "organizeImports": {
          "level": "on",
          "options": {
            "groups": [
              { "source": "builtin" },
              { "source": "external" },
              { "source": "internal", "match": "@company/*" },
              { "source": "relative" }
            ]
          }
        }
      }
    }
  }
}
按子系统设置 includes

每个子系统(linter、formatter、assist)都有自己的 includes,用于精细控制范围。它在 files.includes 之后应用,只能缩小范围,不能扩大范围。

{
  "files": {
    "includes": ["**", "!**/dist"]
  },
  "linter": {
    "includes": ["**", "!**/components/ui"]
  },
  "formatter": {
    "includes": ["**", "!**/components/ui"]
  }
}

此配置会对除 dist/ 和 components/ui 以外的所有内容进行 lint 和格式化,同时仍会在 components/ui 上运行辅助功能(导入整理器)。

覆盖配置

覆盖配置可针对特定文件模式应用不同的设置。可用于调整单个文件的规则(例如,放宽对供应商提供的/shadcn 组件的规则)。字段名为 includes(带 s)。

{
  "overrides": [
    {
      "includes": ["**/components/ui/**"],
      "linter": {
        "rules": {
          "suspicious": { "noDocumentCookie": "off" },
          "style": { "useComponentExportOnlyModules": "off" }
        }
      }
    },
    {
      "includes": ["**/*.test.ts"],
      "linter": {
        "rules": {
          "suspicious": { "noConsole": "off" }
        }
      }
    }
  ]
}
Monorepo 配置

根目录的 biome.json 存放共享配置。软件包配置通过 "extends": "//" 继承:

{
  "$schema": "../../node_modules/@biomejs/biome/configuration_schema.json",
  "extends": "//"
}

在 "extends": "//" 旁添加 linter.rules 部分,即可为每个软件包覆盖特定规则。

配置文件发现(v2.4)

搜索顺序:biome.json -> biome.jsonc -> .biome.json -> .biome.jsonc -> 平台配置目录。

平台配置目录路径:

平台路径
Linux$XDG_CONFIG_HOME/biome(或 ~/.config/biome)
macOS~/Library/Application Support/biome
Windows%APPDATA%\biome\config(即 C:\Users\<user>\AppData\Roaming\biome\config)

v2.4 其他亮点

  • 嵌入式代码片段:Biome 2.4 可格式化并 lint 嵌入在 JavaScript 中的 CSS 和 GraphQL(例如 styled-components、Emotion、gql 模板字面量)。自动生效,无需额外配置。
  • Vue/Svelte 解析器改进:在 .vue 和 .svelte 文件中,noUnusedVariables、useConst、useImportType 和 noUnusedImports 的误报大幅减少。

领域

领域按技术对 lint 规则进行分组。只启用技术栈所需的领域:

{
  "linter": {
    "domains": {
      "react": "recommended",
      "next": "recommended",
      "test": "recommended",
      "types": "all"
    }
  }
}
领域用途自动检测条件
reactReact hooks、JSX 模式react >= 16.0.0
reactNativeReact Native 规则(noReactNativeRawText、noReactNativeLiteralColors、noReactNativeDeepImports、useReactNativePlatformComponents)react-native
nextNext.js 专属规则next >= 14.0.0
solidSolid.js 规则solid-js 依赖
qwikQwik 专属规则@builder.io/qwik
vueVue 专属规则vue
test测试最佳实践(适用于任何框架)jest、mocha、ava 或 vitest
playwrightPlaywright 测试规则@playwright/test
drizzleDrizzle ORM 安全规则drizzle-orm
turborepoTurborepo monorepo 规则turbo
project跨文件分析(noImportCycles、noUnresolvedImports)-
types类型推断规则(noFloatingPromises、noMisusedPromises)-

启用级别: "recommended"(仅稳定规则)、"all"(包含 nursery)、"none"(禁用)。

project 领域会启用需要模块图的规则。types 领域(v2.4)会启用需要类型推断的规则。两者都会触发文件扫描,带来少量额外开销。

类型感知 lint

Biome 2.0 引入了无需 TypeScript 编译器的类型感知 lint。Biome 使用 Rust 实现了自己的类型推断引擎,无需依赖 typescript。

工作原理

启用 types 领域即可激活文件扫描和类型推断。与 typescript-eslint 相比,性能影响极小,因为推断是在原生环境中运行的。

**v2.4.12 改进:**类型感知规则现在可以通过 Pick<T, K>、Omit<T, K>、Partial<T>、Required<T> 和 Readonly<T> 工具类型解析成员(同时保留 optional、readonly 和可空标记),因此规则看到的代码形态与你的代码实际形态一致。

关键规则
规则检测内容
noFloatingPromises未处理的 Promise(缺少 await/return/void)
noMisusedPromises在条件语句、数组回调中使用 Promise
useAwaitThenable对非 thenable 值使用 await
noUnnecessaryConditions始终为 true/false 的条件
useRegexpExec在适合使用 regexp.exec() 时使用 string.match()
useFind使用 array.filter()[0] 而不是 array.find()
useArraySortCompare使用 Array.sort() 时未提供比较函数
noFloatingPromises

影响最大的类型感知规则。用于检测未处理的 Promise:

// ERROR: floating promise
async function loadData() {
  fetch("/api/data");
}

// VALID: awaited
async function loadData() {
  await fetch("/api/data");
}

// VALID: explicitly voided (fire-and-forget)
async function loadData() {
  void fetch("/api/data");
}

与 typescript-eslint 相比,可检测约 75% 的情况,并且每次发布都会改进。v2.4.12 新增了对跨模块泛型包装函数的检测(例如,从另一个文件重新导出的泛型 wrap(fn))。

React Compiler 与 useExhaustiveDependencies 的交互

如果你使用 React Compiler,useExhaustiveDependencies 无法判断编译器是否已为你处理记忆化。许多 React Compiler 用户(包括 Biome 贡献者)会完全禁用此规则:

{
  "linter": {
    "rules": {
      "correctness": {
        "useExhaustiveDependencies": "off"
      }
    }
  }
}

如果保留此规则,请做好抑制某些效果的准备:这些效果有意依赖某个值,但不会在函数体中读取该值(例如,使用 location.pathname 在导航时重新触发)。

与 typescript-eslint 相比的局限性
  • 复杂的泛型类型推断可能会遗漏某些情况
  • 并非完整的类型检查器——可处理常见模式,但无法覆盖所有边缘情况
  • 规则仍处于 nursery 阶段——每次发布都会有所改进
  • 性能优势显著:耗时仅为基于 tsc 的 lint 的一小部分

GritQL 自定义规则

GritQL 是一种用于自定义 lint 规则的声明式模式匹配语言。创建 .grit 文件并将其注册为插件。

{ "plugins": ["./lint-rules/no-object-assign.grit"] }
示例

禁止使用 Object.assign:

`$fn($args)` where {
    $fn <: `Object.assign`,
    register_diagnostic(
        span = $fn,
        message = "Prefer object spread instead of `Object.assign()`"
    )
}

CSS - 强制使用颜色类:

language css;
`$selector { $props }` where {
    $props <: contains `color: $color` as $rule,
    not $selector <: r"\.color-.*",
    register_diagnostic(
        span = $rule,
        message = "Don't set explicit colors. Use `.color-*` classes instead."
    )
}
插件 API

register_diagnostic() 参数:

  • severity - "hint"、"info"、"warn"、"error"(默认值:"error")
  • message(必需)- 诊断消息
  • span(必需)- 要高亮显示的语法节点

支持的目标语言:JavaScript(默认)和 CSS,以及 v2.4 起支持的 JSON(v2.4 发布博客中新增了 JSON;linter/plugins/ 参考页面可能仍只提到 JS/CSS——以博客为准)。使用 biome lint --profile-rules . 对规则和插件执行情况进行性能分析。

抑制模式

单行
// biome-ignore lint/suspicious/noConsole: needed for debugging
console.log("debug info");
文件级
// biome-ignore-all lint/suspicious/noConsole: logger module
范围
// biome-ignore-start lint/style/useConst: legacy code
let x = 1;
let y = 2;
// biome-ignore-end lint/style/useConst
const a = 4; // this line IS checked

biome-ignore-end 是可选的——省略它即可抑制到文件末尾。Biome 要求在冒号后提供说明文本。

迁移

从 ESLint 迁移
pnpm biome migrate eslint --write
pnpm biome migrate eslint --write --include-inspired  # Include non-identical rules

支持 legacy 和 flat 配置、extends 解析、插件(typescript-eslint、react、jsx-a11y、unicorn)以及 .eslintignore。

从 Prettier 迁移
pnpm biome migrate prettier --write

将 tabWidth 映射为 indentWidth,将 useTabs 映射为 indentStyle,将 singleQuote 映射为 quoteStyle,将 trailingComma 映射为 trailingCommas。

从 ESLint + Prettier 组合迁移
pnpm biome migrate eslint --write
pnpm biome migrate prettier --write
pnpm remove eslint prettier eslint-config-prettier eslint-plugin-prettier \
  @typescript-eslint/parser @typescript-eslint/eslint-plugin
rm .eslintrc* .prettierrc* .eslintignore .prettierignore

启用 VCS 集成,因为 ESLint 默认会遵循 gitignore:

{ "vcs": { "enabled": true, "clientKind": "git", "useIgnoreFile": true } }

CLI 参考

biome check(主要命令)
biome check .                    # Check all files
biome check --write .            # Apply safe fixes
biome check --write --unsafe .   # Apply all fixes
biome check --changed .          # Only VCS-changed files
biome check --staged .           # Only staged files
biome ci(CI 模式)
biome ci .                                           # No writes, exit code on errors
biome ci --reporter=github .                         # GitHub annotations
biome ci --reporter=sarif --reporter-file=report.sarif .  # SARIF output
biome lint
biome lint --only=suspicious/noDebugger .    # Single rule
biome lint --skip=project .                  # Skip domain
biome lint --only=types .                    # Only type-aware rules
biome lint --error-on-warnings .             # Warnings become errors
biome lint --enforce-assist .                # Fail when assist actions remain unapplied
biome lint --suppress --reason "tracked in #123" .  # Insert biome-ignore suppressions instead of fixes

--enforce-assist 在 CI 中很有用:导入整理及其他 assist 操作默认不会生成 lint 诊断,因此即使导入顺序未整理,直接运行 biome ci 也可能通过。将 --suppress 与 --reason 配合使用,可批量添加 biome-ignore 注释(Biome 要求在冒号后提供说明文本)。

其他命令
biome format --write .                       # Format only
biome search '`console.$method($args)`' .    # GritQL pattern search
biome rage                                   # Debug info for bug reports
biome explain noFloatingPromises             # Explain a rule

最佳实践

  1. 将 biome check 作为唯一命令——它整合了格式化、代码检查和导入整理
  2. 从 recommended: true 开始——按需禁用单个规则
  3. 启用相关领域——根据技术栈启用 react、next、test、types
  4. 启用 VCS 集成——遵循 .gitignore,并启用 --changed/--staged
  5. 在流水线中使用 biome ci——不会写入文件,退出码清晰
  6. 固定精确版本——避免不同版本发布之间规则意外变更
  7. 每次升级后运行 biome migrate --write
  8. 在提交前钩子中使用 --staged:biome check --staged --write --no-errors-on-unmatched .
  9. 使用 biome lint --profile-rules 分析耗时较长的规则(v2.4)
  10. 使用 GritQL 插件处理项目专属模式,而不是全局禁用规则

注意事项

这些都是曾导致配置损坏、工作树变脏和调试时间浪费的真实错误。编写任何 Biome 配置前请先阅读。

  1. 不存在 files.ignore、files.include、files.exclude。 只有 files.includes(带 s)。对其他任何键,Biome 都会抛出 Found an unknown key。请参阅上面的第一条关键规则。

  2. organizeImports 不是顶层配置键。 在 Biome 2.x 中,它已移至 assist.actions.source.organizeImports。在顶层使用它会导致配置错误。

  3. 禁用 linter 和 formatter 的 overrides 仍会运行 assist。 如果你使用 overrides 跳过生成文件,导入整理器(一种 assist 操作)仍会重写该文件。这会悄悄弄脏你的工作树。请使用 files.includes 的否定模式来完全排除文件。

  4. overrides 字段是 includes(带 s),不是 include。 命名方式与 files.includes 相同。

  5. biome check --write 会在一次运行中执行格式化、代码检查和辅助操作。 这三者中的任何一个都可能修改文件。如果生成文件在运行 check --write 后仍不断变脏,请检查是哪个子系统在处理它——通常是导入整理器(assist),而不是格式化器或代码检查器。

  6. 优先使用 --write,而不是 --fix。 在 biome lint 和 biome format 中,--fix 是 --write 的文档化别名;但 biome check 才是规范入口,且 --write 是所有命令中都有文档说明的标志。请选择 --write 并保持一致。

  7. package.json 无限反复格式化循环。 Biome 的默认 JSON 格式化器使用制表符;pnpm(以及其他一些工具)则使用 2 个空格缩进写入 package.json。每次安装都会重写该文件,随后 biome check --write 又会再次重写,导致每次提交都留下脏文件。可通过以下任一方式修复:排除 package.json(在 files.includes 中使用 "!**/package.json"),或覆盖 JSON 配置以使用空格:

    {
      "overrides": [
        {
          "includes": ["**/package.json"],
          "json": { "formatter": { "indentStyle": "space", "indentWidth": 2 } }
        }
      ]
    }
    

资源

如需查看按类别分类并附有代码示例的详细代码检查规则,请参阅 rules-reference.md。

评论

支持 Markdown