中文
文档
格式化器

格式化器

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

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

内置格式化器

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

格式化器扩展名要求
gofmt.gogofmt 命令可用
mix.ex, .exs, .eex, .heex, .leex, .neex, .sfacemix 命令可用
prettier.js, .jsx, .ts, .tsx, .html, .css, .md, .json, .yaml 及更多 (opens in a new tab)package.json 中有 prettier 依赖
biome.js, .jsx, .ts, .tsx, .html, .css, .md, .json, .yaml 及更多 (opens in a new tab)biome.json(c) 配置文件
zig.zig, .zonzig 命令可用
clang-format.c, .cpp, .h, .hpp, .ino 及更多 (opens in a new tab).clang-format 配置文件
ktlint.kt, .ktsktlint 命令可用
ruff.py, .pyiruff 命令可用且有配置
rustfmt.rsrustfmt 命令可用
cargofmt.rscargo fmt 命令可用
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 命令可用
pint.phpcomposer.json 中有 laravel/pint 依赖
oxfmt (实验性).js, .jsx, .ts, .tsxpackage.json 中有 oxfmt 依赖且设置了实验性环境变量标志
ormolu.hsormolu 命令可用

因此,如果你的项目在 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
    }
  }
}

自定义格式化器

你可以通过指定命令、环境变量和文件扩展名来覆盖内置格式化器或添加新的格式化器:

opencode.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 占位符将被替换为正在格式化的文件路径。