Skip to content

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.gogofmt 命令
rustfmt / cargofmt.rsrustfmt / cargo fmt 命令
ruff.py, .pyiruff 命令且有配置文件
uv.py, .pyiuv 命令
clang-format.c, .cpp, .h, .hpp 等存在 .clang-format 配置文件
ktlint.kt, .ktsktlint 命令
dart.dartdart 命令
shfmt.sh, .bashshfmt 命令
pint.phpcomposer.json 中有 laravel/pint
rubocop / standardrb.rb, .rake 等有对应命令
terraform.tf, .tfvarsterraform 命令
zig.zig, .zonzig 命令
air.Rair 命令
gleam.gleamgleam 命令
mix.ex, .exs 等mix 命令
nixfmt.nixnixfmt 命令
ocamlformat.ml, .mliocamlformat 命令且有 .ocamlformat 配置
dfmt.ddfmt 命令
cljfmt.clj, .cljs, .cljc, .edncljfmt 命令
oxfmt(实验性).js, .jsx, .ts, .tsxpackage.json 中有 oxfmt 且设置了实验性环境变量

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


工作流程

OpenCode 的格式化流程:

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

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


配置

通过 opencode.jsonformatter 字段自定义格式化行为:

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

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

属性类型说明
disabledboolean设为 true 禁用此格式化器
commandstring[]运行格式化的命令
environmentobject运行格式化器时的环境变量
extensionsstring[]此格式化器处理的文件扩展名

禁用所有格式化器

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

禁用特定格式化器

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

自定义格式化器

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

json
{
  "$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 命令即可。