Prettier Docs & Config Examples Guide | Web Formatter Blog

Prettier Docs & Config Examples Guide
A comprehensive guide to configuring and using Prettier for consistent code formatting.
Introduction to Prettier
Prettier is an opinionated code formatter that supports multiple languages and integrates with most editors. It enforces a consistent style by parsing your code and reprinting it with its own rules, taking the maximum line length into account.
Key benefits of using Prettier include:
- Consistent code style across your entire codebase
- Saves time and mental energy by eliminating style debates
- Improves code review processes by focusing on content instead of formatting
- Integrates with most popular editors and build tools
This guide will walk you through everything you need to know about configuring and using Prettier effectively.
Installation
You can install Prettier locally in your project or globally on your machine. Local installation is recommended to ensure all contributors use the same version.
# Local installation (recommended)
npm install --save-dev prettier
# Global installation
npm install --global prettier
To verify your installation:
# For local installation
npx prettier --version
# For global installation
prettier --version
Basic Usage
There are two primary ways to use Prettier: through the command line or integrated with your editor.
Command Line Usage
Format files using the CLI:
# Format a file and overwrite it
npx prettier --write file.js
# Format multiple files
npx prettier --write "src/**/*.{js,jsx,ts,tsx}"
# Check if files are formatted without changing them
npx prettier --check "src/**/*.{js,jsx,ts,tsx}"
Common CLI options:
-
--write
: Rewrites all processed files in place -
--check
: Checks if files are formatted, useful in CI/CD -
--ignore-path
: Specify a custom ignore file -
--config
: Specify a custom config file
Editor Integration
Prettier works best when integrated with your editor to format on save:
Configuration Options
While Prettier is opinionated, it offers configuration options to customize its behavior.
Configuration File Formats
Prettier supports multiple configuration file formats:
-
package.json
- Add a "prettier" key -
.prettierrc
- JSON or YAML format -
.prettierrc.json
,.prettierrc.yml
,{" "}.prettierrc.yaml
-
.prettierrc.js
,prettier.config.js
- JavaScript with module.exports -
.prettierrc.cjs
- CommonJS format for ES modules -
.prettierrc.toml
- TOML format
Example .prettierrc.json:
{
"printWidth": 80,
"tabWidth": 2,
"useTabs": false,
"semi": true,
"singleQuote": false,
"trailingComma": "es5",
"bracketSpacing": true,
"arrowParens": "always"
}
Common Configuration Options
Here are the most commonly used Prettier options:
Option | Default | Description |
---|---|---|
printWidth
|
80 | Maximum line length |
tabWidth
|
2 | Number of spaces per indentation level |
useTabs
|
false | Use tabs instead of spaces |
semi
|
true | Add semicolons at the end of statements |
singleQuote
|
false | Use single quotes instead of double quotes |
trailingComma
|
"es5" | Print trailing commas wherever possible (none, es5, all) |
bracketSpacing
|
true | Print spaces between brackets in object literals |
arrowParens
|
"always" | Include parentheses around a sole arrow function parameter |
File-Specific Overrides
You can specify different formatting options for different file
patterns using the overrides
option:
{
"semi": false,
"overrides": [
{
"files": "*.test.js",
"options": {
"semi": true
}
},
{
"files": ["*.html", "legacy/**/*.js"],
"options": {
"tabWidth": 4
}
}
]
}
This is useful for maintaining different styles for different parts of your codebase or for legacy code.
Ignoring Code
Sometimes you may want to exclude certain files or code blocks from formatting.
Using prettier-ignore
To exclude specific parts of your code from formatting, use comments:
// Normal code that will be formatted
const formattedCode = "This will be formatted";
// prettier-ignore
const unformattedCode = "This will not be formatted";
/* For JSX/HTML content: */
// prettier-ignore
This won't be formatted
Language-specific ignore comments:
-
CSS:
/* prettier-ignore */
-
HTML:
{""}
or{" "}{""}
-
Markdown:
{""}
prettierignore Files
To ignore entire files, create a .prettierignore
file
in your project root:
# Build outputs
dist/
build/
coverage/
# Package files
node_modules/
package-lock.json
yarn.lock
# Generated files
*.min.js
*.bundle.js
# Specific files
legacy-code.js
third-party-lib.js
The .prettierignore
file uses the same format as{" "}
.gitignore
.
Prettier Plugins
Plugins extend Prettier's functionality to support additional languages or customize formatting behavior.
Popular Plugins
- @prettier/plugin-php: Adds PHP support
- @prettier/plugin-ruby: Adds Ruby support
- prettier-plugin-tailwindcss: Sorts Tailwind CSS classes
- prettier-plugin-organize-imports: Organizes imports in TypeScript/JavaScript
- prettier-plugin-svelte: Adds Svelte support
- prettier-plugin-astro: Adds Astro support
Using Plugins
To use a plugin, first install it:
npm install --save-dev prettier-plugin-tailwindcss
Then, Prettier will automatically detect and use the plugin. You can also explicitly specify plugins in your configuration:
{
"plugins": [
"prettier-plugin-tailwindcss"
],
"tailwindConfig": "./tailwind.config.js"
}
Integrations
Prettier works well with other tools in your development workflow.
ESLint Integration
To use Prettier with ESLint:
- Install the required packages:
npm install --save-dev eslint-config-prettier eslint-plugin-prettier
- Update your ESLint configuration:
{
"extends": [
"eslint:recommended",
"plugin:react/recommended",
"prettier" // Must come last to override other configs
],
"plugins": ["prettier"],
"rules": {
"prettier/prettier": "error"
}
}
This setup will run Prettier as an ESLint rule and report formatting differences as ESLint errors.
Git Hooks
Use Git hooks to format code automatically before committing:
- Install husky and lint-staged:
npm install --save-dev husky lint-staged
- Configure in package.json:
{
"scripts": {
"prepare": "husky install"
},
"lint-staged": {
"*.{js,jsx,ts,tsx,css,md,json}": "prettier --write"
}
}
- Set up the pre-commit hook:
npx husky add .husky/pre-commit "npx lint-staged"
Now, Prettier will automatically format your changed files before each commit.
CI/CD Integration
Add Prettier checks to your CI/CD pipeline to ensure all code is properly formatted:
# GitHub Actions example
name: Prettier Check
on:
push:
branches: [ main ]
pull_request:
branches: [ main ]
jobs:
prettier:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
with:
node-version: '16'
cache: 'npm'
- run: npm ci
- run: npx prettier --check .
Configuration Examples
Here are some practical configuration examples for different project types.
JavaScript/TypeScript
A standard configuration for JavaScript/TypeScript projects:
{
"printWidth": 80,
"tabWidth": 2,
"useTabs": false,
"semi": true,
"singleQuote": true,
"trailingComma": "all",
"bracketSpacing": true,
"arrowParens": "always",
"endOfLine": "lf"
}
React Projects
Configuration optimized for React projects:
{
"printWidth": 100,
"tabWidth": 2,
"useTabs": false,
"semi": true,
"singleQuote": true,
"jsxSingleQuote": false,
"trailingComma": "all",
"bracketSpacing": true,
"bracketSameLine": false,
"arrowParens": "always"
}
Vue Projects
Configuration for Vue projects:
{
"printWidth": 100,
"tabWidth": 2,
"useTabs": false,
"semi": true,
"singleQuote": true,
"trailingComma": "all",
"bracketSpacing": true,
"bracketSameLine": false,
"arrowParens": "always",
"vueIndentScriptAndStyle": true
}
CSS/HTML
Configuration for CSS and HTML files:
{
"printWidth": 100,
"tabWidth": 2,
"useTabs": false,
"singleQuote": false,
"htmlWhitespaceSensitivity": "css",
"embeddedLanguageFormatting": "auto"
}
Troubleshooting
Common issues and their solutions:
Issue | Solution |
---|---|
Prettier not formatting files | Check if the file is in .prettierignore or if the file extension is supported |
Conflicts with ESLint | Use eslint-config-prettier to disable conflicting rules |
Formatting not working in editor | Verify the Prettier extension is installed and enabled; check if the correct version is being used |
Different formatting in CI vs locally | Pin the Prettier version in package.json to ensure consistency |
Plugins not working | Ensure plugins are installed and listed in the correct order in your config |
Best Practices
Follow these best practices for a smooth Prettier experience:
- Use local installation: Install Prettier locally in each project to ensure version consistency
- Commit configuration files: Include .prettierrc and .prettierignore in your repository
- Format entire codebase: Run Prettier on your entire codebase before adopting it to avoid large diffs later
- Use editor integration: Configure your editor to format on save for immediate feedback
- Add to CI pipeline: Run Prettier in check mode in your CI to catch unformatted code
- Use with pre-commit hooks: Automatically format code before committing
- Pin the version: Specify an exact Prettier version to ensure consistent formatting
- Document your setup: Include information about your Prettier setup in your project README
Conclusion
Prettier is a powerful tool that eliminates debates about code style and helps teams focus on what matters: writing functional, maintainable code. By following the guidelines in this article, you can effectively integrate Prettier into your workflow and enjoy the benefits of consistent, automatically formatted code.
Remember that while Prettier is opinionated by design, its configuration options provide enough flexibility to adapt to most project requirements. The time saved from not having to manually format code or discuss style preferences in code reviews makes Prettier an invaluable tool for modern development teams.
Start with the defaults, adjust as needed for your team's preferences, and let Prettier handle the rest!