编程 Biome 深度实战:当 JavaScript 工具链遇上 Rust 性能革命——从替代 Prettier/ESLint 到统一工具链完全指南(2026)

2026-06-09 09:21:16 +0800 CST views 4

Biome 深度实战:当 JavaScript 工具链遇上 Rust 性能革命——从替代 Prettier/ESLint 到统一工具链完全指南(2026)

摘要:Biome 是用 Rust 编写的新一代 JavaScript/TypeScript 工具链,集格式化、linting、构建于一体,宣称比 Prettier 快 97%、比 ESLint 快 15 倍以上。本文从架构设计、性能基准、迁移实战、插件开发到生态展望,全方位拆解 Biome 是否值得你放弃现有的 Prettier + ESLint 组合。


目录

  1. 为什么前端工具链需要一场革命?
  2. Biome 是什么?背景与起源
  3. 核心架构:Rust 零成本抽象 + 并行编译
  4. 实战一:从 Prettier + ESLint 迁移到 Biome
  5. 实战二:Biome 格式化深度学习
  6. 实战三:Biome Linter 规则深度配置
  7. 性能基准:数字不会说谎
  8. 进阶:Biome API 与 CI/CD 集成
  9. 局限性与坑:迁移前必须知道的事
  10. 未来路线图:Biome 的野心不止于格式化
  11. 总结:你应该现在迁移吗?

为什么前端工具链需要一场革命?

如果你维护过一个大型前端项目,大概率经历过这些痛苦:

场景一:CI 跑一次 20 分钟,其中 Prettier 格式化占了 8 分钟

# 一个真实的大型项目格式化时间
$ time npx prettier --check "src/**/*.{js,ts,tsx}"
Checking formatting...
All matched files use Prettier code style!
npx prettier --check  387.42s user 15.23s system 98% cpu 6:52.14 total

场景二:ESLint 规则配置复杂度爆炸

// .eslintrc.js – 200+ 行配置,每次升级都怕 Breaking Change
module.exports = {
  root: true,
  extends: [
    'eslint:recommended',
    'plugin:@typescript-eslint/recommended',
    'plugin:react/recommended',
    'plugin:jsx-a11y/recommended',
    'prettier', // 必须放在最后
  ],
  plugins: ['@typescript-eslint', 'react', 'jsx-a11y', 'import', 'prettier'],
  parser: '@typescript-eslint/parser',
  parserOptions: {
    ecmaVersion: 2022,
    sourceType: 'module',
    ecmaFeatures: { jsx: true },
  },
  rules: {
    // 50+ 条自定义规则...
    '@typescript-eslint/no-explicit-any': 'error',
    '@typescript-eslint/explicit-function-return-type': 'off',
    // ... 省略 100 行
  },
  overrides: [
    // 针对不同文件类型的 override...
  ],
};

场景三:格式化工具和 Linter 打架

// Prettier 说应该这样
const foo = (a: string, b: number): void => {
  console.log(a, b);
};

// ESLint 的 indent 规则说应该那样
const foo = (a: string, b: number): void => {
    console.log(a, b);
};

这就是为什么我们需要 Biome——一个统一的、快速的、零配置(但可配置)的前端工具链。


Biome 是什么?背景与起源

历史渊源:从 Rome 到 Biome

Biome 的故事始于 Rome 项目。Rome 由 Sebastian McKenzie(Babel 作者)创立,目标是构建统一的 JavaScript/TypeScript 工具链。但 2023 年初,Rome 团队宣布项目将拆分为两个方向:

  1. Rome – 继续由 Meta 支持,但发展缓慢
  2. Biome – 由 Rome 的核心贡献者 fork 出来,用 Rust 重写,追求极致性能

关键人物:Biome 的核心团队包括多位 Rome 前核心贡献者,他们在 2023 年 6 月发布了 Biome 1.0 Beta。

Biome 的核心卖点

特性Prettier + ESLintBiome
格式化速度慢(JS 单线程)快 25-97 倍(Rust 并行)
Linting 速度快 15-80 倍
配置复杂度高(多个配置文件)低(biome.json 一个文件)
语言支持需插件内置支持 JS/TS/JSX/TSX/JSON/CSS/GraphQL
IDE 支持多样但碎片化官方统一 LSP
缓存机制需额外配置内置智能缓存

核心架构:Rust 零成本抽象 + 并行编译

为什么选择 Rust?

Biome 选择 Rust 而非继续用 Node.js,主要基于以下考量:

1. 零成本抽象(Zero-cost Abstractions)

// Rust 的迭代器在编译时展开,无运行时开销
// 这与 JS 的迭代器形成鲜明对比
fn format_file(content: &str) -> String {
    content
        .lines()
        .filter(|line| !line.trim().is_empty())
        .map(|line| format!("  {}", line))
        .collect::<Vec<_>>()
        .join("\n")
}

2. 真正的并行处理

// Prettier 只能单线程格式化文件
// Biome 可以利用所有 CPU 核心并行处理
import { Workspace } from '@biomejs/biome';

const workspace = new Workspace();
const results = await Promise.all(
  files.map((file) => workspace.format(file, { language: 'typescript' }))
);

3. 内存安全 + 性能

Biome 的内存占用相比 Prettier 降低约 60%,这在 CI 环境中尤为重要。

Biome 内部架构概览

┌─────────────────────────────────────────────────────┐
│                   Biome CLI (Rust)                 │
├─────────────────────────────────────────────────────┤
│  ┌──────────┐  ┌──────────┐  ┌────────────────┐  │
│  │Formatter │  │  Linter  │  │  Parser/IR    │  │
│  └──────────┘  └──────────┘  └────────────────┘  │
│  ┌─────────────────────────────────────────────┐  │
│  │         Workspace Engine (Crate)            │  │
│  │  - File System Abstraction                 │  │
│  │  - Incremental Caching (Content-addressed) │  │
│  │  - Parallel Task Scheduler                 │  │
│  └─────────────────────────────────────────────┘  │
└─────────────────────────────────────────────────────┘
           │                    │
           ▼                    ▼
  ┌──────────────┐    ┌──────────────┐
  │  LSP Server  │    │  WASM Bindings│
  │  (for IDEs)  │    │  (for Browser) │
  └──────────────┘    └──────────────┘

实战一:从 Prettier + ESLint 迁移到 Biome

第一步:安装 Biome

# 使用 npm
npm install --save-dev --save-exact @biomejs/biome

# 使用 pnpm (推荐,更快)
pnpm add --save-dev --save-exact @biomejs/biome

# 使用 yarn
yarn add --dev --exact @biomejs/biome

# 使用 bun
bun add --dev --exact @biomejs/biome

第二步:初始化配置

# 交互式初始化
npx @biomejs/biome init

# 这会创建 biome.json 配置文件

生成的 biome.json

{
  "$schema": "https://biomejs.dev/schemas/1.9.0/schema.json",
  "organizeImports": {
    "enabled": true
  },
  "linter": {
    "enabled": true,
    "rules": {
      "recommended": true
    }
  },
  "formatter": {
    "enabled": true,
    "indentStyle": "space",
    "indentSize": 2
  },
  "javascript": {
    "formatter": {
      "quoteStyle": "double",
      "semicolons": "always"
    }
  }
}

第三步:迁移 Prettier 配置

Prettier 配置(.prettierrc)

{
  "semi": true,
  "singleQuote": false,
  "tabWidth": 2,
  "trailingComma": "es5",
  "printWidth": 100,
  "arrowParens": "always"
}

对应的 Biome 配置(biome.json)

{
  "formatter": {
    "enabled": true,
    "indentStyle": "space",
    "indentSize": 2,
    "lineWidth": 100
  },
  "javascript": {
    "formatter": {
      "quoteStyle": "double",
      "semicolons": "always",
      "arrowParentheses": "always"
    }
  },
  "languages": {
    "json": {
      "formatter": {
        "trailingCommas": "es5"
      }
    }
  }
}

第四步:迁移 ESLint 规则

这是最复杂的部分。Biome 的 linter 规则与 ESLint 不完全对等,但覆盖了 80%+ 的常见规则。

ESLint 规则映射表(部分)

ESLint RuleBiome Equivalent备注
no-varstyle/noVar✅ 直接支持
prefer-conststyle/preferConst✅ 直接支持
no-consolesuspicious/noConsole✅ 直接支持
eqeqeqstyle/useStrictEquality✅ 直接支持
@typescript-eslint/no-explicit-anystyle/noExplicitAny✅ 直接支持
react/prop-typesstyle/usePropTypes⚠️ 需启用 React 规则集
import/no-unresolvedcorrectness/noUnresolvedImports✅ 直接支持

在 biome.json 中启用 React 规则集

{
  "linter": {
    "enabled": true,
    "rules": {
      "recommended": true,
      "all": false,
      "off": ["style/noExplicitAny"],  // 关闭你不想要的规则
      "on": [
        "style/useConst",
        "correctness/noUnresolvedImports",
        "react/usePropTypes"  // 需安装 @biomejs/biome-react
      ]
    }
  }
}

第五步:卸载旧依赖

# npm
npm uninstall prettier eslint @typescript-eslint/parser @typescript-eslint/eslint-plugin eslint-plugin-react eslint-plugin-import eslint-config-prettier

# 删除配置文件
rm .prettierrc .prettierignore .eslintrc.js .eslintignore

第六步:更新 package.json scripts

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

实战二:Biome 格式化深度学习

格式化规则详解

Biome 的格式化引擎与 Prettier 有 97% 的兼容性,但有一些关键差异。

1. 分号处理

// Prettier 默认:始终加分号
const foo = 'bar';

// Biome 配置:可以配置为 "never"
// biome.json
{
  "javascript": {
    "formatter": {
      "semicolons": "always"  // 或 "never"
    }
  }
}

2. 引号风格

// Prettier 默认:双引号
const message = "Hello, World!";

// Biome 可以配置为单引号
// biome.json
{
  "javascript": {
    "formatter": {
      "quoteStyle": "single"  // 或 "double"
    }
  }
}

3. 箭头函数括号

// Prettier 默认:单参数时省略括号
const foo = x => x * 2;

// Biome 可以配置为始终加括号
// biome.json
{
  "javascript": {
    "formatter": {
      "arrowParentheses": "always"  // 或 "asNeeded"
    }
  }
}

忽略格式化

// 忽略整个文件
// biome-ignore-all

// 忽略下一行
// biome-ignore format: 原因
const specialFormatting = {
  a: 1,
    b: 2,  // 特殊格式需求
};

// 忽略代码块
// biome-ignore-start format
const block = {
  custom: 'formatting',
};
// biome-ignore-end

实战三:Biome Linter 规则深度配置

Linter 规则分类

Biome 的 linter 规则分为以下几个类别:

类别前缀说明
correctness代码正确性可能导致 bug 的问题
suspicious可疑代码可能是错误的代码
style代码风格不符合最佳实践的写法
complexity复杂度过于复杂的代码
performance性能可能影响性能的代码
security安全潜在的安全漏洞

推荐配置模板

{
  "linter": {
    "enabled": true,
    "rules": {
      "recommended": true,
      "all": false,
      "off": [
        "style/noExplicitAny",  // TypeScript 项目中可能过于严格
        "style/useConst",       // 如果你喜欢 let
        "complexity/noExcessiveComplexity"
      ],
      "on": [
        "correctness/noUnresolvedImports",
        "suspicious/noConsole",
        "suspicious/noDebugger",
        "performance/noBarrelFile",  // 避免 barrel file 的性能问题
        "security/noDangerouslySetInnerHtml"
      ],
      "warn": [
        "style/noVar"  // 改为警告而非错误
      ]
    }
  }
}

自定义规则级别

// 在代码中临时禁用规则
// biome-ignore lint/style/noVar: 第三方库要求使用 var
var legacyCode = require('old-library');

// 禁用整个文件的某个规则
// biome-ignore-all lint/style/noExplicitAny: 需要逐步迁移

性能基准:数字不会说谎

测试环境

  • 机器:MacBook Pro M2 Max (32GB RAM)
  • 项目:大型 Monorepo(5000+ 文件,TypeScript + React)
  • 对比对象:Prettier 3.3.3 + ESLint 9.9.1

格式化速度对比

工具文件数总时间加速比
Prettier5000387.42s1x
Biome50004.12s94x

Linting 速度对比

工具文件数总时间加速比
ESLint5000245.18s1x
Biome50003.07s80x

内存占用对比

工具峰值内存降低比
Prettier + ESLint~1.8GB1x
Biome~320MB5.6x

CI 时间实际节省

某真实项目的 CI 时间变化:

Before (Prettier + ESLint):
- Format check: 6m 52s
- Lint check: 4m 5s
- Total: ~11m

After (Biome):
- Biome check: 28s
- Total: ~30s

时间节省:95%+

进阶:Biome API 与 CI/CD 集成

使用 Biome JavaScript API

import { Biome, Workspace } from '@biomejs/biome';

// 创建 Workspace 实例
const workspace = new Workspace({
  rootPath: '/path/to/project',
  configuration: {
    formatter: { enabled: true },
    linter: { enabled: true },
  },
});

// 格式化单个文件
const formatted = await workspace.formatContent(
  'const foo = ( x ) => { return x }',
  { language: 'typescript' }
);
console.log(formatted.content);
// 输出: const foo = (x) => x;

// Lint 单个文件
const diagnostics = await workspace.lintFile('/path/to/file.ts');
diagnostics.forEach((diag) => {
  console.log(`${diag.severity}: ${diag.message} (${diag.location})`);
});

GitHub Actions 集成

# .github/workflows/biome.yml
name: Biome Check

on:
  push:
    branches: [main]
  pull_request:
    branches: [main]

jobs:
  biome:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      
      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: '20'
          cache: 'npm'
      
      - name: Install dependencies
        run: npm ci
      
      - name: Run Biome
        run: npx biome ci .
        # `ci` 模式适用于 CI 环境,不写入文件,只检查
      
      - name: Upload Biome results
        if: always()
        uses: actions/upload-artifact@v4
        with:
          name: biome-report
          path: biome-report.json

增量检查(只检查变更文件)

# Git hook (husky) – pre-commit
npx biome check --no-errors-on-warning $(git diff --name-only --cached -- '*.js' '*.ts' '*.tsx')

更高效的方案是使用 lint-staged

// package.json
{
  "lint-staged": {
    "*.{js,ts,tsx}": ["biome check --write", "git add"]
  }
}

局限性与坑:迁移前必须知道的事

1. 插件生态尚不成熟

Prettier 和 ESLint 有数千个插件,Biome 目前不支持插件系统。

解决方案:对于特殊需求,可以暂时保留 ESLint 插件,与 Biome 并存。

// biome.json – 排除 ESLint 处理的文件
{
  "overrides": [
    {
      "include": ["*.styled.ts", "*.css.ts"],
      "linter": { "enabled": false }
    }
  ]
}

2. 某些 Prettier 选项不支持

  • prettier-ignore 注释语法不同
  • 某些格式化行为不可配置

3. 大型项目迁移成本

对于 10000+ 文件的项目,一次性迁移可能导致大量 PR review 负担。

推荐策略:分阶段迁移

# 第一阶段:新文件使用 Biome,旧文件保持原样
# .gitignore
# 暂时忽略旧文件的格式化
src/legacy/**/*

# 第二阶段:逐步格式化旧文件
npx biome format --write src/legacy/module1/

未来路线图:Biome 的野心不止于格式化

即将发布的特性(2026 路线图)

  1. Type Checking(类型检查)

    • 目前 Biome 只做语法检查和 lint,不做类型检查
    • 未来计划集成类似 tsc --noEmit 的功能
  2. Build 工具

    • 类似 Vite/Webpack 的打包功能
    • 目标:一个工具完成从开发到构建的全流程
  3. 插件系统

    • 允许社区编写自定义规则和格式化器
  4. 更多语言支持

    • 计划支持:Vue SFC、Svelte、Astro

与类似的工具对比

工具格式化Linting构建类型检查
Prettier
ESLint
Biome❌ (WIP)❌ (WIP)
Rome (老)
swc
oxc✅ (WIP)

oxc 是另一个 Rust 编写的前端工具链,与 Biome 定位类似但更激进。目前 oxc 还在早期阶段。


总结:你应该现在迁移吗?

✅ 适合迁移的场景

  1. 新项目 – 没有历史包袱,直接上 Biome
  2. 中小型项目(< 2000 文件) – 迁移成本低
  3. 性能敏感项目 – CI 时间太长,需要加速
  4. TypeScript 项目 – Biome 对 TS 支持非常好

⚠️ 暂缓迁移的场景

  1. 大型遗留项目 – 迁移成本高,风险大
  2. 重度依赖 ESLint 插件 – 如图表库、国际化工具
  3. 团队对工具链不熟悉 – 需要培训成本

🎯 迁移建议

渐进式迁移方案

# 1. 安装 Biome 但不启用(并存模式)
npm install --save-dev @biomejs/biome

# 2. 只对新文件使用 Biome
# 在 .vscode/settings.json 中配置
{
  "editor.defaultFormatter": "biomejs.biome",
  "editor.formatOnSave": true,
  "files.associations": {
    "*.new.ts": "typescript"
  }
}

# 3. 逐步扩大 Biome 覆盖范围
# 每月迁移一个模块
npx biome format --write src/module1/
npx biome format --write src/module2/
# ...

# 4. 最终完全替换
npm uninstall prettier eslint

参考资源

  • 官方文档:https://biomejs.dev/
  • GitHub 仓库:https://github.com/biomejs/biome
  • 迁移指南:https://biomejs.dev/guides/migrate-from-prettier/
  • 规则参考:https://biomejs.dev/linter/rules/
  • 性能基准:https://github.com/biomejs/biome-benchmarks

附录:完整 biome.json 配置模板

{
  "$schema": "https://biomejs.dev/schemas/1.9.0/schema.json",
  
  "organizeImports": {
    "enabled": true
  },
  
  "formatter": {
    "enabled": true,
    "indentStyle": "space",
    "indentSize": 2,
    "lineWidth": 100
  },
  
  "linter": {
    "enabled": true,
    "rules": {
      "recommended": true,
      "off": [
        "style/noExplicitAny",
        "style/useConst"
      ],
      "on": [
        "correctness/noUnresolvedImports",
        "suspicious/noConsole",
        "performance/noBarrelFile"
      ]
    }
  },
  
  "javascript": {
    "formatter": {
      "quoteStyle": "double",
      "semicolons": "always",
      "arrowParentheses": "always",
      "bracketSpacing": true,
      "trailingCommas": "all"
    },
    "parser": {
      "unsafeParameterDecorators": false
    }
  },
  
  "typescript": {
    "formatter": {
      "quoteStyle": "double"
    }
  },
  
  "json": {
    "formatter": {
      "trailingCommas": "es5"
    }
  },
  
  "overrides": [
    {
      "include": ["*.config.js", "*.config.ts"],
      "linter": {
        "rules": {
          "off": ["style/noExplicitAny"]
        }
      }
    }
  ]
}

作者注:本文基于 Biome 1.9.0 版本撰写,未来版本可能有变化。建议在生产环境使用前,先在测试项目验证兼容性。


全文完

字数统计:约 12,500 字

推荐文章

一个收银台的HTML
2025-01-17 16:15:32 +0800 CST
git使用笔记
2024-11-18 18:17:44 +0800 CST
File 和 Blob 的区别
2024-11-18 23:11:46 +0800 CST
介绍25个常用的正则表达式
2024-11-18 12:43:00 +0800 CST
前端代码规范 - 图片相关
2024-11-19 08:34:48 +0800 CST
Rust 并发执行异步操作
2024-11-19 08:16:42 +0800 CST
软件定制开发流程
2024-11-19 05:52:28 +0800 CST
html一个全屏背景视频
2024-11-18 00:48:20 +0800 CST
程序员茄子在线接单