Skip to content

格式化器

OpenCode 使用特定语言的格式化器。

OpenCode 在文件被写入或编辑后,会自动使用特定语言的格式化器对文件进行格式化。这确保了生成的代码遵循项目的代码风格。


内置格式化器

OpenCode 为多种流行语言和框架提供了内置的格式化器。以下是格式化器列表、支持的文件扩展名以及所需的命令或配置选项。

格式化器扩展名要求
gofmt.gogofmt 命令可用
mix.ex, .exs, .eex, .heex, .leex, .neex, .sfacemix 命令可用
prettier.js, .jsx, .ts, .tsx, .html, .css, .md, .json, .yaml, 以及 更多package.json 中包含 prettier 依赖
biome.js, .jsx, .ts, .tsx, .html, .css, .md, .json, .yaml, 以及 更多存在 biome.json(c) 配置文件
zig.zig, .zonzig 命令可用
clang-format.c, .cpp, .h, .hpp, .ino, 以及 更多存在 .clang-format 配置文件
ktlint.kt, .ktsktlint 命令可用
ruff.py, .pyiruff 命令可用且带有配置
rustfmt.rsrustfmt 命令可用
uv.py, .pyiuv 命令可用
rubocop.rb, .rake, .gemspec, .rurubocop 命令可用
standardrb.rb, .rake, .gemspec, .rustandardrb 命令可用
htmlbeautifier.erb, .html.erbhtmlbeautifier 命令可用
air.Rair 命令可用
dart.dartdart 命令可用
ocamlformat.ml, .mliocamlformat 命令可用且存在 .ocamlformat 配置文件
terraform.tf, .tfvarsterraform 命令可用
gleam.gleamgleam 命令可用
nixfmt.nixnixfmt 命令可用
shfmt.sh, .bashshfmt 命令可用
oxfmt (实验性).js, .jsx, .ts, .tsxpackage.json 中包含 oxfmt 依赖,并且开启了 实验性环境变量标志

因此,如果你的项目在 package.json 中包含 prettier,OpenCode 将自动使用它。


工作原理

当 OpenCode 写入或编辑文件时,它会:

  1. 根据所有启用的格式化器检查文件扩展名。
  2. 对文件运行相应的格式化器命令。
  3. 自动应用格式化更改。

此过程在后台进行,确保你的代码风格得以维持,无需任何手动步骤。


配置

你可以通过 OpenCode 配置中的 formatter 部分来自定义格式化器。

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

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

属性类型描述
disabledboolean设置为 true 以禁用该格式化器
commandstring[]用于格式化的命令
environmentobject运行格式化器时要设置的环境变量
extensionsstring[]此格式化器应处理的文件扩展名

让我们来看一些示例。


禁用格式化器

要全局禁用 所有 格式化器,请将 formatter 设置为 false

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

要禁用 特定 的格式化器,请将其 disabled 属性设置为 true

opencode.json
{
"$schema": "https://opencode.ai/config.json",
"formatter": {
"prettier": {
"disabled": true
}
}
}
---
### 自定义格式化器
你可以通过指定命令、环境变量和文件扩展名来覆盖内置格式化器或添加新的格式化器:
```json title="opencode.json" {4-14}
{
"$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 占位符 将被替换为正在格式化的文件路径。