OpenCode 代码格式化:自动化多语言代码风格管理

OpenCode 在每次写入或编辑文件后,会自动检测并运行对应语言的格式化工具,包括 Prettier、Biome、gofmt、rustfmt、ruff 等 20+ 种内置格式化器。你也可以通过配置文件自定义、禁用或添加格式化工具。

OpenCode 在写入或编辑文件后,会自动运行语言特定的格式化工具。这确保了 AI 生成的代码始终符合你的项目代码风格,不需要手动执行格式化步骤。


内置格式化器

OpenCode 内置了 20+ 种格式化器,按需自动触发:

格式化器 适用扩展名 触发条件
biome .js, .jsx, .ts, .tsx, .html, .css, .md, .json 等 存在 biome.json(c) 配置文件
prettier .js, .jsx, .ts, .tsx, .html, .css, .md, .json 等 package.json 中有 prettier 依赖
gofmt .go 有 gofmt 命令
rustfmt / cargofmt .rs 有 rustfmt / cargo fmt 命令
ruff .py, .pyi 有 ruff 命令且有配置文件
uv .py, .pyi 有 uv 命令
clang-format .c, .cpp, .h, .hpp 等 存在 .clang-format 配置文件
ktlint .kt, .kts 有 ktlint 命令
dart .dart 有 dart 命令
shfmt .sh, .bash 有 shfmt 命令
pint .php composer.json 中有 laravel/pint
rubocop / standardrb .rb, .rake 等 有对应命令
terraform .tf, .tfvars 有 terraform 命令
zig .zig, .zon 有 zig 命令
air .R 有 air 命令
gleam .gleam 有 gleam 命令
mix .ex, .exs 等 有 mix 命令
nixfmt .nix 有 nixfmt 命令
ocamlformat .ml, .mli 有 ocamlformat 命令且有 .ocamlformat 配置
dfmt .d 有 dfmt 命令
cljfmt .clj, .cljs, .cljc, .edn 有 cljfmt 命令
oxfmt(实验性) .js, .jsx, .ts, .tsx package.json 中有 oxfmt 且设置了实验性环境变量

比如,只要你的项目 package.json 里有 prettier,OpenCode 就会在每次写入 JS/TS 文件后自动运行 Prettier,无需任何额外配置。


工作流程

OpenCode 的格式化流程:

  1. 检测文件扩展名,匹配已启用的格式化器
  2. 运行对应的格式化命令
  3. 自动应用格式化结果

这一切在后台完成,无需手动操作。


配置

通过 opencode.json 的 formatter 字段自定义格式化行为:

{
  "$schema": "https://opencode.ai/config.json",
  "formatter": {}
}

每个格式化器支持以下配置项:

属性 类型 说明
disabled boolean 设为 true 禁用此格式化器
command string[] 运行格式化的命令
environment object 运行格式化器时的环境变量
extensions string[] 此格式化器处理的文件扩展名

禁用所有格式化器

{
  "$schema": "https://opencode.ai/config.json",
  "formatter": false
}

禁用特定格式化器

{
  "$schema": "https://opencode.ai/config.json",
  "formatter": {
    "prettier": {
      "disabled": true
    }
  }
}

自定义格式化器

你可以覆盖内置格式化器,也可以添加全新的格式化器:

{
  "$schema": "https://opencode.ai/config.json",
  "formatter": {
    "prettier": {
      "command": ["npx", "prettier", "--write", "$FILE"],
      "environment": {
        "NODE_ENV": "development"
      },
      "extensions": [".js", ".ts", ".jsx", ".tsx"]
    },
    "custom-markdown-formatter": {
      "command": ["deno", "fmt", "$FILE"],
      "extensions": [".md"]
    }
  }
}

命令中的 $FILE 占位符会被替换为实际的文件路径。


常见问题

Q: 我的项目用了 Biome 又用了 Prettier,OpenCode 会跑哪个?

A: OpenCode 会检测到两个格式化器都满足条件,可能同时运行。建议通过配置禁用其中一个,避免冲突。

Q: 格式化器运行失败了会怎样?

A: 格式化器失败不会阻止文件写入,OpenCode 会记录错误但继续工作。如果格式化一直失败,检查相关命令是否在 PATH 中可用。

Q: 我想对 Python 同时用 ruff 做 lint 和 format,配置上有什么注意?

A: 在 command 中写明 ["ruff", "format", "$FILE"],ruff 默认支持 format 和 check 两种模式,在 opencode.json 中配置 format 命令即可。