主题模式
为项目配置 Biome 格式化
Biome 将格式化和代码检查放在同一个工具中。下面把缩进设为两个空格,JavaScript 使用单引号,并让 Biome 读取项目的 Git 忽略规则。
安装与初始化
安装本地依赖
sh
npm install --save-dev --save-exact @biomejs/biome
npx @biomejs/biome init在项目根目录执行。使用 pnpm 时,安装命令为 pnpm add -D -E @biomejs/biome,初始化为 pnpm exec biome init;Yarn 对应为 yarn add -D -E @biomejs/biome 和 yarn biome init。沿用项目现有包管理器。
配置字段
保留生成的 $schema,按需合并以下字段:
json
{
"formatter": {
"enabled": true,
"indentStyle": "space",
"indentWidth": 2,
"lineEnding": "lf",
"lineWidth": 120
},
"javascript": {
"formatter": {
"quoteStyle": "single",
"semicolons": "asNeeded",
"trailingCommas": "none"
}
},
"vcs": { "enabled": true, "clientKind": "git", "useIgnoreFile": true }
}把这些字段合并到生成的 biome.json,保留生成的 $schema。indentWidth: 2 是两空格,quoteStyle: single 是 JavaScript 单引号,semicolons: asNeeded 只保留语法需要的分号。useIgnoreFile: true 读取 Git 忽略文件。
先检查再写入
sh
npx @biomejs/biome check src
npx @biomejs/biome check --write src第一条只报告;第二条会写文件。先新建 src/biome-demo.js:
js
const greeting = "hello";
console.log(greeting);只看排版时运行 npx @biomejs/biome format src/biome-demo.js,加 --write 才保存。按上面配置,双引号会变为单引号,可省略的分号会移除。再对单个文件运行 check,区分排版差异与 lint 错误。
本次只在本地解析了配置 JSON,没有安装 Biome。实际检查使用项目已锁定的版本,运行 npx @biomejs/biome --version 查看。CI 使用不带 --write 的命令。
常见问题
- 写入后仍报错:查看诊断属于格式还是 lint 规则;
--write不会自动修复所有错误。 - 无变化:检查文件类型是否支持、是否被忽略,以及命令实际运行目录。
- 保存后反复变化:在编辑器里为该语言指定一个默认格式化器,停用重复的保存格式化动作。
- 格式不符合预期:先修改
biome.json,再对小目录重跑;误写的文件从编辑器撤销或备份恢复。
可配合 VS Code 设置指南 排查保存动作冲突。