Hook

Hook tự định dạng code sau khi sửa file

Mỗi lần Claude sửa hoặc tạo file, hook chạy công cụ định dạng phù hợp với đuôi file (Prettier, Ruff, gofmt). Code luôn đúng định dạng mà không cần nhắc trong prompt.

Đã thử với Claude Code 2.1.329

.claude/hooks/format-file.sh
#!/bin/bash
# Formats the file Claude just wrote. Reads the hook input (JSON) on stdin.
file=$(jq -r '.tool_input.file_path // empty')
[ -z "$file" ] || [ ! -f "$file" ] && exit 0

run() { command -v "$1" >/dev/null 2>&1 && "$@" >/dev/null 2>&1; }

case "$file" in
  *.ts|*.tsx|*.js|*.jsx|*.json|*.css|*.md) run npx --no-install prettier --write "$file" ;;
  *.py) run ruff format "$file" ;;
  *.go) run gofmt -w "$file" ;;
  *.swift) run swift-format --in-place "$file" ;;
esac
exit 0  # never block: a formatting problem must not stop Claude's work
.claude/settings.json
{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          {
            "type": "command",
            "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/format-file.sh"
          }
        ]
      }
    ]
  }
}

Lưu ý

  • Cần cài jq và các công cụ định dạng bạn dùng. Thiếu công cụ nào thì đuôi file đó được bỏ qua.
  • Chạy `chmod +x .claude/hooks/format-file.sh` một lần.
  • Nếu `.claude/settings.json` đã có khóa `hooks`, hãy gộp mục `PostToolUse` vào, đừng ghi đè cả file.

Bài học liên quan

Gõ để tìm trong tra cứu, mẫu cấu hình và bài học. Không dấu cũng được.