Prettier - Code Formatter#
What is Prettier?#
Prettier is an opinionated code formatter that enforces a consistent code style across your entire project. It supports multiple languages including JavaScript, TypeScript, CSS, HTML, JSON, Markdown, and more.
Key Benefits#
- ✨ Consistent formatting - No more debates about code style
- ⚡ Save time - Stop manually formatting code
- 🔧 Easy integration - Works with all major editors
- 🎯 Reduces diff noise - Cleaner git diffs focused on logic, not formatting
Installation#
Project Installation (Recommended)#
# Using npm
npm install --save-dev prettier
# Using yarn
yarn add --dev prettier
# Using pnpm
pnpm add -D prettier
Global Installation#
npm install -g prettier
Configuration#
Basic Configuration (.prettierrc)#
Create a .prettierrc file in your project root:
{
"semi": true,
"singleQuote": true,
"tabWidth": 2,
"trailingComma": "es5",
"printWidth": 80,
"arrowParens": "avoid"
}
Configuration Options Explained#
| Option | Description | Default | Example |
|---|---|---|---|
semi |
Add semicolons at end of statements | true |
true / false |
singleQuote |
Use single quotes instead of double | false |
true / false |
tabWidth |
Number of spaces per indentation level | 2 |
2 / 4 |
trailingComma |
Add trailing commas where valid | "es5" |
"none" / "es5" / "all" |
printWidth |
Line length before wrapping | 80 |
80 / 100 / 120 |
arrowParens |
Parentheses around arrow function parameters | "always" |
"always" / "avoid" |
endOfLine |
Line ending style | "lf" |
"lf" / "crlf" / "auto" |
Alternative Configuration Formats#
Prettier also supports:
// .prettierrc.js
module.exports = {
semi: true,
singleQuote: true,
tabWidth: 2,
};
# .prettierrc.yaml
semi: true
singleQuote: true
tabWidth: 2
Or in package.json:
{
"prettier": {
"semi": true,
"singleQuote": true
}
}
Using Prettier#
Command Line#
# Format a single file
prettier --write src/index.js
# Format all JavaScript files
prettier --write "src/**/*.js"
# Format multiple file types
prettier --write "src/**/*.{js,jsx,ts,tsx,json,css,md}"
# Check if files are formatted (CI)
prettier --check "src/**/*.{js,jsx,ts,tsx}"
# Format stdin and output to stdout
echo "const x = {a:1,b:2}" | prettier --parser babel
Package.json Scripts#
Add these scripts to your package.json:
{
"scripts": {
"format": "prettier --write \"src/**/*.{js,jsx,ts,tsx,json,css,md}\"",
"format:check": "prettier --check \"src/**/*.{js,jsx,ts,tsx,json,css,md}\""
}
}
Then run:
npm run format # Format all files
npm run format:check # Check formatting (for CI)
.prettierignore File#
The .prettierignore file tells Prettier which files and directories to skip. It uses the same syntax as .gitignore.
Creating .prettierignore#
Create a .prettierignore file in your project root:
# Dependencies
node_modules
package-lock.json
yarn.lock
pnpm-lock.yaml
# Build outputs
dist
build
out
.next
.cache
# Coverage reports
coverage
*.lcov
# Environment files
.env
.env.local
.env.production
# Logs
*.log
logs
# OS files
.DS_Store
Thumbs.db
# IDE
.vscode
.idea
# Temporary files
*.tmp
*.temp
# Generated files
*.min.js
*.min.css
public/assets
Common Ignore Patterns#
Ignore Build Artifacts#
dist/
build/
*.bundle.js
Ignore Generated Code#
# Auto-generated by tools
generated/
__generated__/
*.generated.ts
Ignore Large Data Files#
# Don't format large JSON files
data/*.json
fixtures/**
Ignore Specific Directories#
# Legacy code - don't reformat yet
legacy/
vendor/
third-party/
.prettierignore Best Practices#
- Start with .gitignore: Often your
.prettierignoremirrors.gitignore - Ignore dependencies: Always ignore
node_modules - Ignore build outputs: Don't format generated files
- Be explicit: Comment why files are ignored
- Keep it minimal: Only ignore what's necessary
Editor Integration#
VS Code#
- Install the Prettier extension
- Add to
.vscode/settings.json:
{
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnSave": true,
"[javascript]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[typescript]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[json]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
}
}
WebStorm / IntelliJ#
- Go to Settings → Languages & Frameworks → JavaScript → Prettier
- Set path to Prettier package
- Enable On save or On Reformat Code
Sublime Text#
Install JsPrettier package via Package Control.
Vim/Neovim#
Use plugins like prettier/vim-prettier or integrate with ALE/CoC.
Git Integration#
Pre-commit Hook with Husky#
Install dependencies:
npm install --save-dev husky lint-staged
Add to package.json:
{
"lint-staged": {
"*.{js,jsx,ts,tsx,json,css,md}": [
"prettier --write"
]
}
}
Setup Husky:
npx husky init
echo "npx lint-staged" > .husky/pre-commit
Now files are automatically formatted before each commit! 🎉
CI/CD Integration#
GitHub Actions#
name: Prettier Check
on: [pull_request]
jobs:
prettier:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
with:
node-version: '18'
- run: npm ci
- run: npm run format:check
GitLab CI#
prettier:
stage: test
script:
- npm ci
- npm run format:check
Common Configurations#
React/Next.js Project#
{
"semi": true,
"singleQuote": true,
"jsxSingleQuote": false,
"tabWidth": 2,
"trailingComma": "es5",
"printWidth": 100,
"arrowParens": "avoid",
"endOfLine": "lf"
}
TypeScript Project#
{
"semi": true,
"singleQuote": true,
"tabWidth": 2,
"trailingComma": "all",
"printWidth": 120,
"arrowParens": "always"
}
Minimalist Config#
{
"singleQuote": true,
"trailingComma": "es5"
}
Troubleshooting#
Prettier Not Formatting on Save#
- Check VS Code settings for
editor.formatOnSave - Verify Prettier is set as default formatter
- Check for conflicting formatters (ESLint, etc.)
- Restart editor
Conflicting with ESLint#
Install compatibility packages:
npm install --save-dev eslint-config-prettier eslint-plugin-prettier
Update .eslintrc.json:
{
"extends": ["eslint:recommended", "prettier"],
"plugins": ["prettier"],
"rules": {
"prettier/prettier": "error"
}
}
Files Not Being Ignored#
- Check
.prettierignoresyntax - Ensure file is in project root
- Try absolute paths or
**/prefix - Check for typos in patterns
Advanced Usage#
Ignore Specific Code Blocks#
// prettier-ignore
const matrix = [
[1, 0, 0],
[0, 1, 0],
[0, 0, 1]
];
<!-- prettier-ignore -->
<div class="keep-this-formatting" style="color: red">
Content
</div>
/* prettier-ignore */
.selector {
color: red;
margin: 0;
}
Format Specific File Types#
# Only JavaScript
prettier --write "**/*.js"
# Only TypeScript
prettier --write "**/*.{ts,tsx}"
# Only stylesheets
prettier --write "**/*.{css,scss,less}"
Override Options for Specific Files#
In .prettierrc.json:
{
"semi": true,
"overrides": [
{
"files": "*.md",
"options": {
"printWidth": 100
}
},
{
"files": "*.json",
"options": {
"tabWidth": 4
}
}
]
}
Summary#
Prettier is essential for maintaining consistent code style in modern development:
- 🚀 Quick setup - Install and configure in minutes
- 🔄 Automatic formatting - Integrates with editors and git hooks
- 🎯 Opinionated - Fewer decisions, more coding
- 🛡️ .prettierignore - Control what gets formatted
- 🤝 Team consistency - Everyone uses the same style
Getting Started Checklist
- [ ] Install Prettier in your project
- [ ] Create
.prettierrcconfiguration - [ ] Create
.prettierignorefile - [ ] Add format scripts to
package.json - [ ] Enable format on save in your editor
- [ ] Set up pre-commit hooks with Husky
- [ ] Add Prettier check to CI/CD pipeline
Pro Tip
Don't overthink the configuration - Prettier's defaults are excellent. Start with minimal config and only customize what truly matters to your team.