Code Formatting
Code formatting ensures consistent style across your codebase, making it easier to read, maintain, and collaborate on. Prettier is our recommended tool for automatic code formatting.
Why Use Prettier?
Section titled “Why Use Prettier?”- Consistency: Enforces uniform code style across the entire team
- Automation: Formats code automatically, reducing manual effort
- Fewer Debates: Eliminates discussions about code style preferences
- Better Diffs: Consistent formatting makes code reviews more focused on logic
Setting Up Prettier
Section titled “Setting Up Prettier”Installation
Section titled “Installation”# Install Prettier as a dev dependencynpm install --save-dev prettier
# Install the Prettier extension for VS Code# Search for "Prettier - Code formatter" in VS Code extensions
# Install Prettier as a dev dependencyyarn add --dev prettier
Configuration
Section titled “Configuration”Create a .prettierrc
file in your project root:
{ "semi": true, "trailingComma": "es5", "singleQuote": true, "printWidth": 80, "tabWidth": 2, "useTabs": false, "bracketSpacing": true, "arrowParens": "avoid"}
Prettier Extension for VS Code
Section titled “Prettier Extension for VS Code”Direct Integration (Recommended)
Section titled “Direct Integration (Recommended)”Instead of always running the format script manually, you can use the Prettier - Code formatter extension for automatic formatting:
# Install via VS Code1. Open VS Code2. Go to Extensions (Ctrl+Shift+X)3. Search "Prettier - Code formatter"4. Click Install on the official Prettier extension
Create or update .vscode/settings.json
in your project:
{ "editor.defaultFormatter": "esbenp.prettier-vscode", "editor.formatOnSave": true, "editor.formatOnPaste": true, "editor.codeActionsOnSave": { "source.fixAll": true }, "[javascript]": { "editor.defaultFormatter": "esbenp.prettier-vscode" }, "[typescript]": { "editor.defaultFormatter": "esbenp.prettier-vscode" }, "[json]": { "editor.defaultFormatter": "esbenp.prettier-vscode" }}
Configuration Priority
Section titled “Configuration Priority”Prettier follows this configuration priority order:
.prettierrc
file in your project root (recommended)- VS Code settings (
settings.json
) - Default Prettier settings
Example .prettierrc configuration:
{ "semi": true, "trailingComma": "es5", "singleQuote": true, "printWidth": 80, "tabWidth": 2, "useTabs": false, "bracketSpacing": true, "arrowParens": "avoid"}
VS Code Settings Alternative
Section titled “VS Code Settings Alternative”If you prefer to configure Prettier through VS Code settings instead of .prettierrc
:
{ "editor.defaultFormatter": "esbenp.prettier-vscode", "editor.formatOnSave": true, "prettier.semi": true, "prettier.singleQuote": true, // ...}
Configuration Options
Section titled “Configuration Options”Essential Settings
Section titled “Essential Settings”Option | Description | Recommended Value |
---|---|---|
semi | Add semicolons at end of statements | true |
singleQuote | Use single quotes instead of double | true |
trailingComma | Add trailing commas where valid | "es5" |
printWidth | Line length before wrapping | 80 |
tabWidth | Number of spaces per indentation | 2 |
Ignoring Files
Section titled “Ignoring Files”Create a .prettierignore
file to exclude files from formatting:
# Build outputsdist/build/coverage/
# Dependenciesnode_modules/
# Generated files*.min.js*.bundle.js
# Configuration files that need specific formattingpackage-lock.jsonyarn.lock
# Documentation that has specific formattingCHANGELOG.md
Format Script
Section titled “Format Script”The Primary Format Script
Section titled “The Primary Format Script”Add this essential script to your package.json
:
{ "scripts": { "format": "prettier --write ." }}
What the Format Script Does
Section titled “What the Format Script Does”When you run npm run format
, this script:
- Finds all files in your project directory (
.
) - Applies Prettier formatting to supported file types
- Writes changes back to files (
--write
flag) - Respects your configuration from
.prettierrc
and.prettierignore
Supported file types include:
- JavaScript (
.js
,.jsx
) - TypeScript (
.ts
,.tsx
) - JSON (
.json
) - CSS/SCSS (
.css
,.scss
) - HTML (
.html
) - Markdown (
.md
,.mdx
) - YAML (
.yml
,.yaml
)
How Both Approaches Work Together
Section titled “How Both Approaches Work Together”Extension for Development
Section titled “Extension for Development”- Format on save: Automatically formats files when you save
- Format on paste: Formats pasted code instantly
- Real-time feedback: See formatting applied immediately
- Individual workflow: Each developer gets instant formatting
Script for Team Consistency
Section titled “Script for Team Consistency”- Batch formatting: Format entire project at once
- CI/CD integration: Ensure consistency in automated processes
- New team members: Easy way to format everything correctly
- Git hooks: Automatic formatting before commits
# Use both approaches:# 1. Extension formats as you work# 2. Script ensures everything is formatted
# Before committing, run the script to be sure:npm run format
# Then commit your properly formatted codegit add .git commit -m "Add new feature with proper formatting"
Common Formatting Examples
Section titled “Common Formatting Examples”Before and After
Section titled “Before and After”Before Prettier:
const user={name:"John",age:25,city:"New York"};
function getUserInfo(id){return fetch(`/api/users/${id}`).then(response=>response.json()).catch(error=>{console.error("Error fetching user:",error);throw error;});}
After Prettier:
const user = { name: 'John', age: 25, city: 'New York' };
function getUserInfo(id) { return fetch(`/api/users/${id}`) .then(response => response.json()) .catch(error => { console.error('Error fetching user:', error); throw error; });}
Best Practices
Section titled “Best Practices”Recommended Workflow
Section titled “Recommended Workflow”- Install Prettier extension in VS Code for immediate formatting
- Add format script to package.json for batch operations
- Use .prettierrc for team-wide configuration consistency
- Run format script before important commits
# Daily workflow:# 1. Code with extension auto-formatting# 2. Before major commits:npm run formatgit add .git commit -m "Feature complete with consistent formatting"
- ✅ Use the Prettier extension for real-time formatting
- ✅ Add the format script for batch formatting
- ✅ Create .prettierrc for team consistency
- ✅ Format before committing important changes
Don’ts
Section titled “Don’ts”- ❌ Don’t rely only on manual formatting
- ❌ Don’t mix different formatting configs across team members
- ❌ Don’t ignore the format script in CI/CD
- ❌ Don’t format generated files or dependencies
Troubleshooting
Section titled “Troubleshooting”Common Issues
Section titled “Common Issues”Prettier not working in VS Code:
- Ensure the Prettier extension is installed and enabled
- Check that Prettier is set as the default formatter
- Verify your
.prettierrc
file has valid JSON syntax
Conflicts with ESLint:
Install eslint-config-prettier
to disable ESLint formatting rules:
npm install --save-dev eslint-config-prettier
Add to your .eslintrc
:
{ "extends": ["eslint:recommended", "prettier"]}
Further Reading
Section titled “Further Reading”- Prettier Official Documentation
- Prettier Playground - Test configurations online