Biome 自定义插件开发指南

Biome 自定义插件开发指南

编程
2026年12月1日
2188 words, about 11 分钟

简介

什么是 Biome

Biome 是一个快速、统一的 JavaScript/TypeScript 工具链,提供格式化、linting、重构等功能。它支持通过 Grit 语言编写自定义 lint 规则。

什么是 Grit

Grit 是一种声明式的模式匹配语言,专门用于代码分析和转换。它允许你:

  • 匹配特定的代码结构
  • 检查代码模式
  • 报告自定义诊断信息
  • 自动修复问题(可选)

为什么使用 Grit 编写插件

  • 声明式语法:无需手动遍历 AST
  • 跨语言支持:支持 JS/TS/JSX/TSX
  • 强大的模式匹配:支持正则表达式、上下文匹配
  • 集成简单:与 Biome 无缝集成

Grit 语言基础

基本结构

language js  // 指定语言

pattern PatternName() {
  // 模式定义
}

// 主逻辑
{
  // 匹配和检查逻辑
}

关键概念

1. 模式(Pattern)

模式用于匹配代码结构:

pattern FunctionCall() {
  JsCallExpression(callee = "t")  // 匹配 t()
}

常用节点类型:

  • JsStringLiteralExpression - 字符串字面量
  • JsTemplateExpression - 模板字符串
  • JsCallExpression - 函数调用
  • JsxElement - JSX 元素
  • JsxText - JSX 文本
  • JsxAttribute - JSX 属性

2. 变量绑定

使用 $variable 绑定匹配的部分:

JsStringLiteralExpression() as $literal where {
  $content = text($literal)
}

3. 条件检查

使用 where 添加条件:

where {
  $content = text($node),
  $content <: r"regex_pattern",  // 正则匹配
  ! $node <: within SomeContext()  // 排除特定上下文
}

4. 注册诊断

使用 register_diagnostic 报告问题:

register_diagnostic(
  span = $node,              // 错误位置
  message = "Error message", // 错误消息
  severity = "error"         // 严重程度:error, warning, info
)

实战:i18n 检查插件

需求分析

在国际化项目中,需要确保:

  1. 所有中文字符串都使用翻译函数包裹(如 t() 或 <Trans>)
  2. 避免硬编码的中文文本
  3. 排除不需要翻译的上下文(如控制台日志、特定函数调用)

完整插件代码

language js

// 定义忽略的函数名模式
pattern IgnoredFunctionNames() {
  r"^(?:.*\.)?(?:t|i18n|translate|require|console\.[a-zA-Z]+)$"
}

// 定义忽略的上下文
pattern IgnoredContext() {
  or {
    JsCallExpression(callee = IgnoredFunctionNames()),
    JsxExpressionAttributeValue(),
    JsBinaryExpression()
  }
}

// 主检查逻辑
or {
  // 检查字符串字面量
  JsStringLiteralExpression() as $literal where {
    $content = text($literal),
    $content <: r".*\p{Han}.*",  // 匹配包含中文的字符串
    ! $literal <: within IgnoredContext(),
    register_diagnostic(
      span = $literal,
      message = "Chinese string must be wrapped with t() or <Trans> for translation",
      severity = "error"
    )
  },
  // 检查模板字符串
  JsTemplateChunkElement() as $template_chunk where {
    $content = text($template_chunk),
    $content <: r".*\p{Han}.*",
    ! $template_chunk <: within IgnoredContext(),
    register_diagnostic(
      span = $template_chunk,
      message = "Chinese template string must be wrapped with t() or <Trans> for translation",
      severity = "error"
    )
  },
  // 检查 JSX 文本
  JsxText() as $jsx_text where {
    $content = text($jsx_text),
    $content <: r".*\p{Han}.*",
    ! $jsx_text <: within `<Trans $...>$...</Trans>`,
    register_diagnostic(
      span = $jsx_text,
      message = "JSX Chinese text must be wrapped with t() or <Trans> for translation",
      severity = "error"
    )
  },
  // 检查 JSX 属性
  JsxAttribute(name = $name, initializer = $val) as $attr where {
    $val_text = text($val),
    $val_text <: r"^(?:[\"'`]|\{\s*[\"'`]).*\p{Han}.*",
    $name_text = text($name),
    ! $name_text <: r"^(?:className|styleName|style|type|key|id|width|height)$",
    register_diagnostic(
      span = $attr,
      message = "JSX attribute with Chinese must be wrapped with t() or <Trans> for translation",
      severity = "error"
    )
  }
}

代码详解

1. 忽略函数模式

pattern IgnoredFunctionNames() {
  r"^(?:.*\.)?(?:t|i18n|translate|require|console\.[a-zA-Z]+)$"
}

这个正则表达式匹配:

  • t - 翻译函数
  • i18n - i18n 对象
  • translate - 翻译函数
  • require - CommonJS 导入
  • console.log 等 - 控制台方法

2. 忽略上下文

pattern IgnoredContext() {
  or {
    JsCallExpression(callee = IgnoredFunctionNames()),  // 忽略翻译函数调用
    JsxExpressionAttributeValue(),  // 忽略 JSX 表达式属性
    JsBinaryExpression()  // 忽略二元表达式
  }
}

3. 中文检测

使用 Unicode 属性匹配中文字符:

$content <: r".*\p{Han}.*"  // 匹配任何包含中文字符的字符串

\p{Han} 是 Unicode 属性,匹配所有汉字字符。

4. JSX 特定检查

检查 JSX 文本是否被 <Trans> 组件包裹:

! $jsx_text <: within `<Trans $...>$...</Trans>`

检查 JSX 属性(排除样式相关属性):

! $name_text <: r"^(?:className|styleName|style|type|key|id|width|height)$"

使用方法

  1. 将 .grit 文件放入项目目录(如 biome-plugins/)

  2. 在 biome.json 中配置:

    {
      "plugins": ["./biome-plugins/js-i18n-check.grit"]
    }
  3. 运行检查:

    biome check --apply

实战:代码规范检查插件

需求分析

在大型项目中,需要统一代码规范:

  1. 禁止使用硬编码的域名和品牌名
  2. 强制使用封装后的工具函数(如 dayjs.tz、存储工具等)
  3. 避免使用不兼容某些环境的 API(如 window.open)

完整插件代码

language js

or {
  // 检查字符串字面量中的硬编码域名
  JsStringLiteralExpression() as $literal where {
    $content = text($literal),
    or {
      {
        $content <: r".*TODO_BRAND_NAME.*",
        register_diagnostic(
          span = $literal,
          message = "Brand name and logo should not be hardcoded, use configuration instead",
          severity = "error"
        )
      },
      {
        $content <: r".*TODO_DOMAIN\.com.*",
        register_diagnostic(
          span = $literal,
          message = "Hardcoded domain detected, use centralized URL constants instead",
          severity = "error"
        )
      }
    }
  },
  // 检查模板字符串中的硬编码域名
  JsTemplateExpression() as $template where {
    $content = text($template),
    or {
      {
        $content <: r".*TODO_BRAND_NAME.*",
        register_diagnostic(
          span = $template,
          message = "Brand name and logo should not be hardcoded, use configuration instead",
          severity = "error"
        )
      },
      {
        $content <: r".*TODO_DOMAIN\.com.*",
        register_diagnostic(
          span = $template,
          message = "Hardcoded domain detected, use centralized URL constants instead",
          severity = "error"
        )
      }
    }
  },
  // 检查 JSX 文本中的品牌名
  JsxText() as $jsx_text where {
    $content = text($jsx_text),
    $content <: r".*TODO_BRAND_NAME.*",
    register_diagnostic(
      span = $jsx_text,
      message = "Brand name and logo should not be hardcoded, use configuration instead",
      severity = "error"
    )
  },
  // 检查 dayjs 使用是否带时区
  `dayjs($...)` as $call where {
    register_diagnostic(
      span = $call,
      message = "When using dayjs, must call .tz() method to ensure correct timezone. Example: dayjs.tz(timestamp)",
      severity = "error"
    )
  },
  // 检查是否直接使用 localStorage/sessionStorage
  `localStorage.setItem($...)` as $call where {
    register_diagnostic(
      span = $call,
      message = "Use wrapped storage utility instead of direct localStorage access",
      severity = "error"
    )
  },
  `sessionStorage.setItem($...)` as $call where {
    register_diagnostic(
      span = $call,
      message = "Use wrapped storage utility instead of direct sessionStorage access",
      severity = "error"
    )
  },
  // 检查是否直接使用 window.open
  `window.open($...)` as $call where {
    register_diagnostic(
      span = $call,
      message = "Avoid using window.open directly, use wrapped utility function instead",
      severity = "error"
    )
  }
}

代码详解

1. 硬编码检测

检测字符串、模板字符串、JSX 文本中的硬编码内容:

$content <: r".*TODO_BRAND_NAME.*"
$content <: r".*TODO_DOMAIN\.com.*"

使用正则表达式匹配特定模式,报告错误并要求使用配置或常量替代。

2. 函数调用模式匹配

使用反引号语法匹配特定的函数调用:

`dayjs($...)`                 // 匹配 dayjs() 调用
`localStorage.setItem($...)`  // 匹配 localStorage.setItem()
`window.open($...)`           // 匹配 window.open()

$... 表示任意参数。

3. 强制使用封装函数

通过禁止直接使用某些 API,强制开发者使用封装后的工具函数:

  • dayjs() → dayjs.tz()(确保时区正确)
  • localStorage → 使用封装的存储工具
  • window.open() → 使用兼容多端的工具函数

使用方法

  1. 将配置添加到 biome.json:

    {
      "plugins": [
        "./biome-plugins/js-i18n-check.grit",
        "./biome-plugins/js-code-standards.grit"
      ]
    }
  2. 运行检查并自动修复:

    biome check --apply
  3. 临时忽略某行:

    // biome-ignore lint: 原因说明
    const domain = "example.com";

高级技巧

1. 正则表达式技巧

// 匹配特定模式
r".*TODO_BRAND_NAME.*"

// 匹配开头或结尾
r"^(?:[\"'`]|\{\s*[\"'`])"  // 匹配以引号开头

// Unicode 属性
r".*\p{Han}.*"  // 中文
r".*\p{Latin}.*"  // 拉丁字母

2. 上下文匹配

// 检查节点是否在特定上下文中
$node <: within SomePattern()

// 排除特定上下文
! $node <: within SomePattern()

// 示例:检查是否在 Trans 组件中
within `<Trans $...>$...</Trans>`

3. 多条件组合

where {
  // AND 条件
  condition1,
  condition2,

  // OR 条件
  or {
    condition3,
    condition4
  },

  // NOT 条件
  ! condition5
}

4. 提取文本和属性

// 提取节点文本
$content = text($node)

// 提取属性
JsxAttribute(name = $name, initializer = $val)
$name_text = text($name)
$val_text = text($val)

最佳实践

1. 命名规范

  • 文件名:使用 kebab-case,如 js-i18n-check.grit
  • 模式名:使用 PascalCase,如 IgnoredFunctionNames
  • 变量名:使用 snake_case,如 $template_chunk

2. 错误消息

  • 清晰明确:说明问题和解决方法
  • 英文优先:便于国际化团队使用
  • 提供示例:如 Example: dayjs.tz(timestamp)

3. 性能优化

  • 限制正则表达式复杂度
  • 合理使用 within 上下文匹配
  • 避免过多的 or 分支

4. 测试

创建测试用例验证插件:

// 应报错的代码
const msg = "中文";  // ❌ 应该用 t() 包裹

// 不应报错的代码
const msg = t("中文");  // ✅ 已包裹
const msg = "English";  // ✅ 非中文
console.log("中文");    // ✅ 在忽略列表中

5. 渐进式采用

  • 先在新代码中使用
  • 使用 // biome-ignore 注释临时跳过
  • 逐步修复存量问题

常见问题

Q: 如何调试 Grit 插件?

A: 使用 biome check --verbose 查看详细错误信息。可以在插件中添加临时诊断输出。

Q: 如何处理误报?

A: 调整 IgnoredContext 模式,添加更多排除规则。

Q: 支持自动修复吗?

A: Grit 支持 rewrite 语句进行自动修复,但 i18n 场景通常需要人工介入,所以本示例只报告错误。

Q: 如何匹配复杂模式?

A: 使用 pattern 定义子模式,然后组合使用。参考 Grit 官方文档了解更多模式匹配语法。

参考资源