如何在 Next.js 项目中设置 Husky + Biome(2026 指南)

发布: (2025年12月8日 GMT+8 01:35)
4 min read
原文: Dev.to

Source: Dev.to

介绍

大多数 JavaScript/TypeScript 项目使用 ESLint + Prettier 进行 lint 和格式化。
Biome —— 一款快速、全能的 Rust 驱动工具 —— 可以取代两者。将 Biome 与 Husky 结合,可确保每次提交自动符合你的格式化和 lint 标准。

本指南展示了在 Next.js 项目中使用 npm 设置 Husky + Biome 的最简方法,且不使用 lint-staged,也不保留任何旧的 ESLint/Prettier 配置。

为什么选择 Biome?

  1. 快速 —— 基于 Rust 的引擎 → 极快的格式化和 lint。
  2. 全能 —— 同时处理 lint、格式化、自动修复以及导入组织。
  3. 简洁 —— 只需一个配置文件:biome.json
  4. 无需 lint-staged —— Biome 原生支持仅检查暂存文件。

第一步 — 安装 Husky 与 Biome

npm install -D @biomejs/biome husky

第二步 — 初始化 Husky

npx husky init

这会创建:

.husky/
  pre-commit

第三步 — 添加 Biome 配置

创建名为 biome.json 的文件:

{
  "$schema": "https://biomejs.dev/schemas/2.3.8/schema.json",
  "vcs": {
    "enabled": true,
    "clientKind": "git",
    "useIgnoreFile": true
  },
  "files": {
    "ignoreUnknown": false
  },
  "formatter": {
    "enabled": true,
    "indentStyle": "tab"
  },
  "linter": {
    "enabled": true,
    "rules": {
      "recommended": true
    }
  },
  "javascript": {
    "formatter": {
      "quoteStyle": "double"
    }
  },
  "assist": {
    "enabled": true,
    "actions": {
      "source": {
        "organizeImports": "on"
      }
    }
  }
}

第 3.5 步 — 在 package.json 中添加 Husky 与 Biome 脚本

更新 scripts 部分:

{
  "scripts": {
    "prepare": "husky",
    "lint": "biome check .",
    "format": "biome format --write ."
  }
}
  • prepare → 自动安装 Husky Git 钩子。
  • lint → 运行完整的 Biome 检查。
  • format → 格式化整个项目。

第四步 — 配置 pre‑commit 钩子

.husky/pre-commit 替换为:

#!/bin/sh
npx biome check --staged --write

**注意:**Biome 已移除 --apply 参数;现在使用 --write 才是正确的修复标志。此命令仅在提交前对暂存文件进行格式化 + lint。

第五步 — 测试配置

  1. 编写凌乱的代码,例如:

    const  a={b:1}
  2. 暂存并提交:

    git add .
    git commit -m "test"

Biome 会自动修复为:

const a = { b: 1 };

如果提交成功,说明一切正常。

第六步 —(可选)移除 ESLint 与 Prettier

如果你完全转向 Biome,删除以下内容:

  • .eslintrc.*
  • .prettierrc
  • 所有 ESLint 相关的包
  • 所有 Prettier 相关的包

Biome 完全取代了它们。

最终代码片段

下面的内容可直接复制使用。

package.json 脚本

{
  "scripts": {
    "prepare": "husky",
    "lint": "biome check .",
    "format": "biome format --write ."
  }
}

.husky/pre-commit

#!/bin/sh
npx biome check --staged --write

biome.json

{
  "$schema": "https://biomejs.dev/schemas/2.3.8/schema.json",
  "vcs": {
    "enabled": true,
    "clientKind": "git",
    "useIgnoreFile": true
  },
  "files": {
    "ignoreUnknown": false
  },
  "formatter": {
    "enabled": true,
    "indentStyle": "tab"
  },
  "linter": {
    "enabled": true,
    "rules": {
      "recommended": true
    }
  },
  "javascript": {
    "formatter": {
      "quoteStyle": "double"
    }
  },
  "assist": {
    "enabled": true,
    "actions": {
      "source": {
        "organizeImports": "on"
      }
    }
  }
}

结论

使用 Biome + Husky 是在 2026 年保持代码质量的最简方案:

  • 比 ESLint/Prettier 更快
  • 依赖更少
  • 现代化的 Git‑hook 工作流
  • 自动仅对暂存文件进行检查
  • 配置简单

非常适合 Next.js、React、TypeScript 与 Node 项目。

Back to Blog

相关文章

阅读更多 »