Tips and tricks
git: Add a precommit hook to add prettier to staged files
Posted on October 26 2025 / in WordPress
Without husky / lint-staged
If you want to do it without husky and lint-staged you just need this file in .githooks/pre-commit
#!/bin/sh
set -e
# Determine repository root
ROOT_DIR="$(git rev-parse --show-toplevel)"
echo "pre-commit: running in $ROOT_DIR"
# Collect staged files (added, copied, modified, renamed)
# Show raw list for debugging
STAGED_ALL=$(git diff --cached --name-only --diff-filter=ACMR)
echo "$STAGED_ALL" | sed 's/^/pre-commit: raw staged: /' || true
# Filter by extensions (case-insensitive) using awk for portability
STAGED_FILES=$(printf "%s\n" "$STAGED_ALL" | awk 'BEGIN{IGNORECASE=1} /\.(js|jsx|ts|tsx|json|css|scss|less|html|md|yml|yaml)$/')
echo "$STAGED_FILES" | sed 's/^/pre-commit: staged (filtered): /' || true
# Nothing to format
if [ -z "$STAGED_FILES" ]; then
exit 0
fi
# Find a prettier binary (prefer workspace installs)
USE_NPX=0
if [ -x "$ROOT_DIR/business-library/node_modules/.bin/prettier" ]; then
PRETTIER_BIN="$ROOT_DIR/business-library/node_modules/.bin/prettier"
elif [ -x "$ROOT_DIR/node_modules/.bin/prettier" ]; then
PRETTIER_BIN="$ROOT_DIR/node_modules/.bin/prettier"
else
USE_NPX=1
fi
echo "Running Prettier on staged files..."
# Format each staged file and add it back to the index
for FILE in $STAGED_FILES; do
if [ $USE_NPX -eq 1 ]; then
npx prettier --write "$FILE"
else
"$PRETTIER_BIN" --write "$FILE"
fi
git add "$FILE"
done
exit 0
if you want you can install prettier as a dev dependency locally or have it globally
npm i -D prettier
you can have a .prettierrc like:
{
"bracketSpacing": true,
"printWidth": 120,
"proseWrap": "always",
"quoteProps": "as-needed",
"singleQuote": true,
"tabWidth": 2,
"trailingComma": "all",
"useTabs": false
}
also you need this command to make it executable
chmod +x .githooks/pre-commit
set the hooks with
git config core.hooksPath .githooks
With husky / lint-staged
do this in /.husky/pre-commit
#!/bin/sh
# Source Husky shim if available (created by `husky install`), otherwise continue standalone
if [ -f "$(dirname -- "$0")/_/husky.sh" ]; then
. "$(dirname -- "$0")/_/husky.sh"
fi
# Run lint-staged from business-library so it picks up its config
cd "$(git rev-parse --show-toplevel)/business-library" || exit 1
echo "husky: running lint-staged in $(pwd)"
# Prefer local binary if installed, fallback to npx
if [ -x "./node_modules/.bin/lint-staged" ]; then
./node_modules/.bin/lint-staged
else
npx lint-staged
fi
In package.json you need the step inside “scripts”
"prepare": "husky"
and
"lint-staged": {
"*.{ts,tsx,js,jsx,html,css,scss,json,md,yml,yaml}": "prettier --write"
}