Add to Claude Code
525 addsInstall this Claude Code hook.
Name: Auto-format on Save
Save to: ~/.claude/hooks/auto-format-on-save.sh
Make executable: yes
---
#!/usr/bin/env node
// Hook type: PostToolUse
// Trigger: Write, Edit (file tool calls)
//
// Reads the tool result from stdin, extracts the file path,
// and runs Prettier on it if a Prettier config is present.
import { execSync } from "child_process"
import { existsSync } from "fs"
import { join } from "path"
import { readFileSync } from "fs"
const input = JSON.parse(readFileSync("/dev/stdin", "utf8"))
// Only act on Write / Edit tool calls
const toolName = input?.tool_name ?? ""
if (!["Write", "Edit"].includes(toolName)) process.exit(0)
const filePath = input?.tool_input?.file_path ?? input?.tool_input?.path
if (!filePath) process.exit(0)
// Detect Prettier config in project root (walk up from file)
function findPrettierConfig(start: string): boolean {
const configs = [
".prettierrc",
".prettierrc.json",
".prettierrc.js",
".prettierrc.cjs",
"prettier.config.js",
"prettier.config.cjs",
"prettier.config.mjs",
]
let dir = start
while (dir !== "/") {
if (configs.some((c) => existsSync(join(dir, c)))) return true
dir = join(dir, "..")
}
return false
}
const dir = filePath.replace(/\/[^\/]+$/, "")
if (!findPrettierConfig(dir)) process.exit(0)
try {
execSync(`npx prettier --write "${filePath}"`, { stdio: "inherit" })
} catch {
// Non-fatal: Prettier may not support this file type
}
Paste into Claude Code to add this hook. Review the source first.
This is a shell script. Review the source before running: view raw.
How to add
Full guide →Click Add, then paste into Claude Code. Claude will configure the hook in your settings.
Target: .claude/settings.json → hooks