Back to Hooks
Auto Import Sort
PostToolUseAutomatically sorts and organizes imports after file edits using the project's import ordering rules
importsformattingorganizationeslint
Hook Script
#!/bin/bash
# Auto Import Sort Hook
# Sorts imports after file edits using ESLint's import sorting rule
FILE_PATH="$TOOL_INPUT_file_path"
# Only process JS/TS files
if [[ ! "$FILE_PATH" =~ \.(js|jsx|ts|tsx|mjs|mts)$ ]]; then
exit 0
fi
# Check if eslint is available
if ! command -v npx &> /dev/null; then
exit 0
fi
# Run ESLint's import sorting fix
npx eslint --fix --rule '{"import/order": ["error", {"groups": ["builtin", "external", "internal", "parent", "sibling", "index"], "newlines-between": "always", "alphabetize": {"order": "asc"}}]}' "$FILE_PATH" 2>/dev/null
# If eslint fails (no config, etc.), try with prettier-plugin-organize-imports
if [ $? -ne 0 ]; then
npx prettier --write --plugin prettier-plugin-organize-imports "$FILE_PATH" 2>/dev/null
fi
exit 0
Settings Configuration
{
"hooks": {
"PostToolUse": [
{
"matcher": "Edit|Write",
"command": "./hooks/import-sort.sh"
}
]
}
}How to use
- Create a hooks directory in your project: mkdir hooks
- Save the hook script as hooks/import-sort.sh
- Make it executable: chmod +x hooks/import-sort.sh
- Add the configuration to your Claude Code settings
- Restart Claude Code to apply changes