JavaScript Prettier Tutorial: Setup to Save-on-Format | Web Formatter Blog
{post.title}
{post.excerpt}
{post.tags.length > 0 && (Web Formatter Team
Code Formatting Experts
Introduction to Prettier
Prettier is an opinionated code formatter that supports many languages, including JavaScript. It enforces a consistent style by parsing your code and reprinting it with its own rules. Unlike linters that check for code quality issues, Prettier focuses solely on code formatting, making it a perfect companion to tools like ESLint.
Benefits of Using Prettier
Using Prettier offers several advantages for both individual developers and teams:
- Consistent code style across your entire codebase, regardless of who wrote it
- Saves time by eliminating debates about style and formatting in code reviews
- Improves code readability with standardized formatting
- Catches syntax errors early, as Prettier can't format invalid code
- Integrates with most editors and build tools for a seamless workflow
- Reduces cognitive load by handling formatting decisions automatically
Installation and Setup
To get started with Prettier, you'll need to install it in your project and create some configuration files:
# Install Prettier as a dev dependency
npm install --save-dev prettier
# Create a configuration file
echo {} > .prettierrc.json
# Create an ignore file
echo "node_modules\\ndist\\nbuild\\n.next\\n.cache" > .prettierignore
Adding NPM Scripts
Add these scripts to your package.json to make Prettier easier to use:
{
"scripts": {
"format": "prettier --write \\"**/*.{js,jsx,ts,tsx,json,css,md}\\"",
"format:check": "prettier --check \\"**/*.{js,jsx,ts,tsx,json,css,md}\\""
}
}
Now you can run npm run format
to format all files
or npm run format:check
to check for formatting
issues without changing files.
Configuration Options
Customize Prettier with these common options in your .prettierrc.json file:
{
"printWidth": 80,
"tabWidth": 2,
"useTabs": false,
"semi": true,
"singleQuote": false,
"trailingComma": "es5",
"bracketSpacing": true,
"arrowParens": "always",
"endOfLine": "lf"
}
Configuration Explanation
- printWidth: Maximum line length before wrapping
- tabWidth: Number of spaces per indentation level
- useTabs: Use tabs instead of spaces
- semi: Add semicolons at the end of statements
- singleQuote: Use single quotes instead of double quotes
- trailingComma: Print trailing commas wherever possible when multi-line
- bracketSpacing: Print spaces between brackets in object literals
- arrowParens: Include parentheses around a sole arrow function parameter
- endOfLine: Line feed only (lf), carriage return only (cr), or carriage return + line feed (crlf)
Editor Integration
Set up Prettier to format on save in your editor for the best experience:
VS Code
- Install the Prettier extension from the marketplace
-
Add to settings.json:
{ "editor.formatOnSave": true, "editor.defaultFormatter": "esbenp.prettier-vscode", "[javascript]": { "editor.defaultFormatter": "esbenp.prettier-vscode" }, "[javascriptreact]": { "editor.defaultFormatter": "esbenp.prettier-vscode" }, "[typescript]": { "editor.defaultFormatter": "esbenp.prettier-vscode" }, "[typescriptreact]": { "editor.defaultFormatter": "esbenp.prettier-vscode" } }
WebStorm / IntelliJ IDEA
- Go to Preferences → Languages & Frameworks → JavaScript → Prettier
- Check "On save"
- Set the Prettier package path to your node_modules/prettier
Pre-commit Hooks with Husky and lint-staged
Ensure all committed code is formatted by setting up pre-commit hooks:
# Install husky and lint-staged
npm install --save-dev husky lint-staged
# Initialize husky
npx husky install
npm set-script prepare "husky install"
npx husky add .husky/pre-commit "npx lint-staged"
# Add configuration to package.json
Add this configuration to your package.json:
{
"lint-staged": {
"*.{js,jsx,ts,tsx}": [
"prettier --write",
"eslint --fix"
],
"*.{json,css,md}": [
"prettier --write"
]
}
}
Now, whenever you commit code, Prettier will automatically format your staged files.
Integrating with ESLint
Prettier works well with ESLint, but you need to configure them to avoid conflicts:
# Install eslint-config-prettier to disable formatting rules in ESLint
npm install --save-dev eslint-config-prettier
# Install eslint-plugin-prettier to run Prettier as an ESLint rule
npm install --save-dev eslint-plugin-prettier
Update your .eslintrc.json file:
{
"extends": [
"eslint:recommended",
"plugin:react/recommended", // If using React
"prettier" // Must be last to override other configs
],
"plugins": ["prettier"],
"rules": {
"prettier/prettier": "error"
}
}
CI Integration
Add Prettier checks to your CI pipeline to ensure all code follows your formatting standards:
# Example GitHub Actions workflow
name: Code Quality
on:
push:
branches: [ main ]
pull_request:
branches: [ main ]
jobs:
format:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
with:
node-version: '18'
cache: 'npm'
- run: npm ci
- run: npm run format:check
Troubleshooting Common Issues
Resolving Conflicts with ESLint
If you're seeing conflicts between Prettier and ESLint:
- Make sure eslint-config-prettier is the last item in your extends array
- Check that you don't have formatting rules in your ESLint config that conflict with Prettier
- Try running ESLint with the --fix option first, then Prettier
Files Not Being Formatted
If some files aren't being formatted:
- Check your .prettierignore file to make sure they're not excluded
- Verify the file extensions in your npm scripts or lint-staged config
- Make sure the files are properly detected by your editor's Prettier plugin
Advanced Prettier Usage
Prettier Plugins
Extend Prettier's capabilities with plugins:
- prettier-plugin-tailwindcss: Automatically sorts Tailwind CSS classes
- @trivago/prettier-plugin-sort-imports: Sorts import statements
- prettier-plugin-organize-imports: Organizes and removes unused TypeScript imports
File-specific Configuration
You can specify different formatting rules for different file types:
{
"semi": false,
"singleQuote": true,
"overrides": [
{
"files": "*.md",
"options": {
"printWidth": 100,
"proseWrap": "always"
}
},
{
"files": "*.json",
"options": {
"printWidth": 200
}
}
]
}
Conclusion
Prettier simplifies JavaScript code formatting, ensuring consistency across your team. By integrating it into your workflow with editor support and pre-commit hooks, you can maintain clean, readable code with minimal effort.
Remember that the goal of Prettier is to stop all the ongoing debates over styles. Its opinionated nature means you might not agree with all its formatting decisions, but the consistency it brings to your codebase is worth the trade-off.
Start using Prettier today, and you'll wonder how you ever managed without it!