Configurable utility to auto-format staged files using Prettier with customizable file extensions and hooks directory
This package requires Prettier as a peer dependency. Make sure you have Prettier installed in your project before using prettier-staged.
Supported Prettier versions: >=2.0.0
If you don't have Prettier installed, you'll need to install it first:
# For development dependency (recommended)
npm i -D prettier
# Or globally
npm i -g prettierTo use as a dev dependency
# Install prettier if you don't have it
npm i -D prettier
# Then install prettier-staged
npm i -D @iamandersonp/prettier-stagedTo use as a global
# Install prettier globally if you don't have it
npm i -g prettier
# Then install prettier-staged globally
npm i -g @iamandersonp/prettier-stagedOne-line installation (recommended):
# Development dependencies
npm i -D prettier @iamandersonp/prettier-staged
# Global installation
npm i -g prettier @iamandersonp/prettier-stagedNo setup required! 🎉
When you install prettier-staged as a dependency, it automatically adds the prettier-staged script to your package.json. You can start using it immediately:
npm run prettier-stagedManual setup (only if automatic setup fails): If for some reason the automatic script addition doesn't work, you can add it manually:
{
"scripts": {
"prettier-staged": "prettier-staged"
}
}By default, prettier-staged formats these file types: html, ts, scss, css, json, js
You can customize which file extensions to format by creating a .env file in your project root:
# .env
EXTENSIONS=js,jsx,ts,tsx,css,scssExamples of custom configurations:
# React project
EXTENSIONS=js,jsx,ts,tsx,css,scss
# Vue project
EXTENSIONS=vue,js,ts,css,scss
# TypeScript-only project
EXTENSIONS=ts,tsx
# Full-stack project
EXTENSIONS=html,js,jsx,ts,tsx,vue,css,scss,less,json
# With quotes and spaces (automatically cleaned)
EXTENSIONS="js, jsx, ts, tsx"
EXTENSIONS='vue, css, scss'If no .env file exists or EXTENSIONS is not specified, the default extensions will be used.
When installed as a dependency (not during local development), prettier-staged automatically copies a pre-commit hook to your project's hooks directory. This provides a ready-to-use solution for formatting staged files.
You can configure the hooks directory and file extensions using an optional .env file in your project root:
# .env (optional)
HOOKS_DIR=.git-hooks # Default hooks directory
EXTENSIONS=html,ts,scss,css,json,js # Default file extensions
# Customize as needed:
HOOKS_DIR=custom-hooks
HOOKS_DIR="my hooks" # With spaces (quotes optional)
EXTENSIONS=js,jsx,ts,tsx # Custom file extensions
EXTENSIONS="vue,svelte,astro" # Framework-specific filesIf no .env file exists, the default values will be used:
- HOOKS_DIR:
.git-hooks - EXTENSIONS:
html,ts,scss,css,json,js
Fully automatic (recommended):
When you install prettier-staged, a .env file is automatically created from the template!
🎯 No manual steps required - the installation automatically:
- Copies
.env.exampletemplate to your project - Renames it to
.envfor immediate use - Smart .env handling: If
.envalready exists, automatically adds any missing variables (HOOKS_DIR, EXTENSIONS) - Preserves existing
.envfiles (creates.env.exampleas backup if.envalready exists) - Flexible detection: Recognizes variables with various formats (with/without spaces, quotes, etc.)
Examples of variable formats automatically detected:
# All these formats are recognized and preserved:
HOOKS_DIR=.git-hooks # Standard format
HOOKS_DIR = .git-hooks # With spaces
HOOKS_DIR = .git-hooks # Extra whitespace
HOOKS_DIR=".git-hooks" # With quotes
EXTENSIONS=js,ts,css # Standard format
EXTENSIONS = "js, ts, css" # Flexible spacingIntelligent .env management:
- ✅ New projects: Creates complete
.envfrom template - ✅ Existing .env: Analyzes and adds only missing variables
- ✅ Preserves customizations: Never overwrites existing variable values
- ✅ Smart detection: Handles various spacing and quote formats
- ✅ Non-destructive: Maintains your existing configuration
Optional customization:
Edit .env to customize your configuration if needed:
# Hooks directory
HOOKS_DIR=.git-hooks # Use default
# or
HOOKS_DIR=git-hooks # Custom directory
# File extensions to format
EXTENSIONS=html,ts,scss,css,json,js # Use default
# or
EXTENSIONS=js,jsx,ts,tsx # JavaScript/TypeScript only
EXTENSIONS=vue,svelte,astro # Framework-specificManual setup (rarely needed):
In the unlikely case that automatic setup fails, you can create your own .env file with the configuration above.
When installed as a dependency, prettier-staged automatically:
-
Pre-commit hook: Copies a
{HOOKS_DIR}/pre-commitfile that:- Skips formatting during merge conflicts
- Formats staged files with Prettier
- Re-stages formatted files automatically
-
Configuration file: Automatically creates or updates a
.envfile with:- Smart analysis: Checks existing
.envfiles for missing variables - Auto-completion: Adds
HOOKS_DIR=.git-hooksandEXTENSIONS=html,js,ts,scss,css,jsonif missing - Preserves customizations: Never overwrites existing variable values
- Flexible format support: Detects variables with various spacing and quote formats
- Ready-to-use configuration for immediate use
- Safe handling: creates
.env.examplebackup when needed
- Smart analysis: Checks existing
-
NPM script: Adds
"prettier-staged": "prettier-staged"to yourpackage.jsonscripts:- Safe operation - won't overwrite existing scripts
- Creates
scriptssection if it doesn't exist - Enables running
npm run prettier-stagedimmediately
- ✅ New project: Creates complete
.envfrom template → Ready to use immediately - ✅ Existing .env: Intelligently analyzes and adds missing variables (HOOKS_DIR, EXTENSIONS)
- ✅ Preserves settings: Never overwrites your existing variable values
- ✅ Format flexible: Detects variables with spaces, quotes, and various formatting
- ✅ Safe operation: Creates
.env.examplebackup when needed - ✅ Zero setup: Works out-of-the-box for both new and existing projects
After installation, run this command in your project root to use the copied hook:
# Using default .git-hooks directory
git config core.hooksPath .git-hooks# Or if you customized HOOKS_DIR in .env:
git config core.hooksPath your-custom-directoryPro tip: The installation script automatically configures Git for you, so this step is usually not needed!
- ✅ Safe: Only copies files if they don't exist (won't overwrite)
- ✅ Smart: Only installs when added as a dependency, not during development
- ✅ Complete: Copies hook, creates configuration file AND adds NPM script
- ✅ Non-destructive: Won't overwrite existing package.json scripts or .env files
- ✅ Executable: Automatically sets proper permissions (
chmod +x) - ✅ Configurable: Hooks directory can be customized via
.envfile - ✅ Auto-configured: Git hooks path is set automatically during installation
- ✅ Zero-setup: Creates working
.envconfiguration automatically
# All these formats are automatically detected and supported:
# Hooks directory:
HOOKS_DIR=.git-hooks # Basic format
HOOKS_DIR=".git-hooks" # With double quotes
HOOKS_DIR='.git-hooks' # With single quotes
HOOKS_DIR = .git-hooks # With spaces around equals
HOOKS_DIR = .git-hooks # With extra whitespace
HOOKS_DIR=custom-hooks-dir # Custom directory name
HOOKS_DIR="hooks with spaces" # Directories with spaces
# File extensions:
EXTENSIONS=html,js,ts,scss,css,json # Basic format
EXTENSIONS="js,jsx,ts,tsx" # With double quotes
EXTENSIONS='vue,svelte,astro' # With single quotes
EXTENSIONS = js, ts, css, scss # With spaces (auto-trimmed)
EXTENSIONS = "js, ts, css" # Extra whitespace and quotesSmart detection features:
- 🔍 Flexible parsing: Detects variables regardless of spacing or quote style
- 🛡️ Error resilient: Falls back to defaults if format is invalid
- 🔄 Auto-completion: Adds missing variables to existing
.envfiles - ✨ Format preservation: Maintains your existing style when adding variables
Note: If the .env file doesn't exist or has errors, the default values are used automatically:
- HOOKS_DIR:
.git-hooks - EXTENSIONS:
html,ts,scss,css,json,js
If you prefer a custom implementation, you can create your own pre-commit hook using this example (adjust the hooks directory as needed):
#!/bin/sh
# Función para leer extensiones desde .env
get_extensions_from_env() {
local env_file=".env"
local default_extensions="html|ts|scss|css|json|js"
if [ ! -f "$env_file" ]; then
echo "$default_extensions"
return
fi
# Buscar EXTENSIONS en .env
local extensions=$(grep "^EXTENSIONS=" "$env_file" 2>/dev/null | cut -d'=' -f2- | tr -d '"' | tr -d "'")
if [ -n "$extensions" ]; then
# Convertir comas a | para el regex
echo "$extensions" | sed 's/,/|/g' | sed 's/ //g'
else
echo "$default_extensions"
fi
}
if git ls-files -u | grep -q .; then
echo "⚠️ Merge in progress. Skipping Prettier to avoid issues."
exit 0
fi
npm run prettier-staged
# Obtener extensiones desde .env y construir patrón dinámico
EXTENSIONS_PATTERN=$(get_extensions_from_env)
STAGED_FILES=$(git diff --name-only --cached --diff-filter=ACM | grep -E "\.($EXTENSIONS_PATTERN)$")
if [ -n "$STAGED_FILES" ]; then
echo "$STAGED_FILES" | xargs git add
fi-
Install the package:
npm install -D @iamandersonp/prettier-staged
-
Everything is set up automatically! ✨
The installation process automatically:
- 🔗 Adds
"prettier-staged": "prettier-staged"to your package.json scripts - 📁 Creates
.envconfiguration file (ready to use!) - 🎯 Copies and configures the pre-commit hook
- ⚡ Zero manual configuration needed!
- 🔗 Adds
-
Optional: Customize your configuration:
# Edit the automatically created .env file (optional) # Defaults work great for most projects! vim .env # or code .env, nano .env, etc.
-
Start using it immediately:
# Run prettier-staged manually npm run prettier-staged # Or just make commits - the pre-commit hook will run automatically! git add . git commit -m "feat: add new feature"
-
Optional: Verify the setup:
git config core.hooksPath # Should show your hooks directory ls -la .git-hooks/ # Should show the pre-commit hook cat .env # See your active configuration npm run prettier-staged # Test the script works
# Run all tests
npm test
# Run tests in watch mode (automatically re-run on file changes)
npm run test:watch
# Run tests with coverage report
npm run test:coverageCurrent test coverage: >95% including:
- ✅ Successful file formatting scenarios
- ✅ No files to format scenarios
- ✅ Error handling (Prettier not found, syntax errors, general errors)
- ✅ Edge cases (files with spaces, whitespace trimming, all supported extensions)
- ✅ Extensions configuration from
.envfile (custom extensions, fallback to defaults, error handling) - ✅ Hooks directory configuration from
.envfile
The tests use mocks to simulate Git commands and Prettier execution without running actual commands, making tests fast and reliable.
All history of changes are located on CHANGELOG.md.