Formatters

OpenCode tự động format code sau khi viết hoặc chỉnh sửa.


Tổng quan

OpenCode tự động format files sau khi được viết hoặc edit, sử dụng các formatters dành riêng cho từng ngôn ngữ. Điều này đảm bảo code được generate theo đúng coding style của project bạn.


Built-in Formatters

FormatterExtensionsYêu cầu
prettier.js, .jsx, .ts, .tsx, .html, .css, .md, .json, .yamlprettier trong package.json
biome.js, .jsx, .ts, .tsx, .html, .css, .md, .jsonbiome.json(c) config file
gofmt.gogofmt command
rustfmt.rsrustfmt command
cargofmt.rscargo fmt command
ruff.py, .pyiruff command
dart.dartdart command
shfmt.sh, .bashshfmt command
clang-format.c, .cpp, .h, .hpp.clang-format config

Nếu project có prettier trong package.json, OpenCode sẽ tự động dùng nó.


Cách hoạt động

Khi OpenCode viết hoặc edit file:

  1. Kiểm tra extension với tất cả formatters đã bật
  2. Chạy formatter command phù hợp
  3. Áp dụng formatting changes tự động

Cấu hình

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

Disable formatters

Tắt tất cả:

{ "formatter": false }

Tắt một formatter cụ thể:

{
  "formatter": {
    "prettier": { "disabled": true }
  }
}

Custom formatters

{
  "formatter": {
    "prettier": {
      "command": ["npx", "prettier", "--write", "$FILE"],
      "environment": { "NODE_ENV": "development" },
      "extensions": [".js", ".ts", ".jsx", ".tsx"]
    },
    "custom-md": {
      "command": ["deno", "fmt", "$FILE"],
      "extensions": [".md"]
    }
  }
}

$FILE sẽ được thay bằng đường dẫn file đang format.