
Format Code with Prettier in Visual Studio Code
Prettier is an opinionated code formatter that has become the go-to solution for maintaining consistent code style across development teams. When integrated with Visual Studio Code, it automatically formats your JavaScript, TypeScript, CSS, HTML, JSON, and dozens of other file types according to predefined rules, eliminating debates about code style and reducing time spent on manual formatting. This guide will walk you through setting up Prettier in VS Code, configuring it for different workflows, comparing it with alternatives, and troubleshooting common issues that developers encounter during implementation.
How Prettier Works with Visual Studio Code
Prettier operates as a code formatter that parses your code into an Abstract Syntax Tree (AST), then reprints it with consistent styling rules. Unlike linters that focus on code quality and potential bugs, Prettier exclusively handles code formatting – indentation, line breaks, quotes, semicolons, and spacing.
The VS Code integration happens through the official Prettier extension, which acts as a bridge between the editor and the Prettier engine. When you trigger formatting (manually or automatically), VS Code sends your code to Prettier, which processes it according to your configuration and returns the formatted result.
Prettier supports over 20 languages out of the box, including JavaScript, TypeScript, Flow, JSX, JSON, CSS, SCSS, Less, HTML, Vue, Angular, GraphQL, Markdown, and YAML. For languages not natively supported, community plugins extend functionality to handle additional file types.
Step-by-Step Setup Guide
Getting Prettier running in VS Code involves installing the extension and configuring your preferences. Here’s the complete setup process:
Installing the Prettier Extension:
- Open VS Code and navigate to the Extensions panel (Ctrl+Shift+X)
- Search for “Prettier – Code formatter” by Prettier
- Click Install on the official extension (it should have millions of downloads)
- Reload VS Code if prompted
Setting Prettier as Default Formatter:
Open VS Code settings (Ctrl+,) and add these configurations:
{
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnSave": true,
"editor.formatOnPaste": true,
"editor.formatOnType": false
}
For language-specific formatting, you can override the default formatter:
{
"[javascript]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[typescript]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[json]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
}
}
Creating a Prettier Configuration File:
Create a .prettierrc
file in your project root with your preferred settings:
{
"semi": true,
"trailingComma": "es5",
"singleQuote": true,
"printWidth": 100,
"tabWidth": 2,
"useTabs": false,
"bracketSpacing": true,
"arrowParens": "avoid",
"endOfLine": "lf"
}
Alternatively, you can use .prettierrc.js
for more complex configurations:
module.exports = {
semi: true,
trailingComma: 'es5',
singleQuote: true,
printWidth: 100,
tabWidth: 2,
useTabs: false,
bracketSpacing: true,
arrowParens: 'avoid',
endOfLine: 'lf',
overrides: [
{
files: '*.json',
options: {
printWidth: 200,
},
},
],
};
Setting up .prettierignore:
Create a .prettierignore
file to exclude files and directories:
node_modules/
dist/
build/
coverage/
*.min.js
*.min.css
package-lock.json
yarn.lock
Real-World Configuration Examples
Different projects require different formatting approaches. Here are configurations for common scenarios:
React/Next.js Project Configuration:
{
"semi": true,
"trailingComma": "es5",
"singleQuote": true,
"printWidth": 80,
"tabWidth": 2,
"useTabs": false,
"bracketSpacing": true,
"bracketSameLine": false,
"arrowParens": "avoid",
"endOfLine": "lf",
"jsxSingleQuote": true
}
Node.js Backend Configuration:
{
"semi": true,
"trailingComma": "all",
"singleQuote": true,
"printWidth": 120,
"tabWidth": 4,
"useTabs": false,
"bracketSpacing": true,
"arrowParens": "always",
"endOfLine": "lf"
}
Team Collaboration Setup:
For teams working on VPS or dedicated servers, consistency across development environments is crucial. Use package.json scripts to ensure everyone uses the same Prettier version:
{
"scripts": {
"format": "prettier --write .",
"format:check": "prettier --check .",
"format:staged": "pretty-quick --staged"
},
"devDependencies": {
"prettier": "^3.0.0",
"pretty-quick": "^3.1.3"
}
}
Integrate with Husky for pre-commit hooks:
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"
npx pretty-quick --staged
Comparison with Alternative Formatters
Feature | Prettier | ESLint –fix | Beautify | StandardJS |
---|---|---|---|---|
Language Support | 20+ languages | JavaScript/TypeScript mainly | HTML/CSS/JS | JavaScript only |
Configuration Options | Limited (opinionated) | Extensive | Many options | Zero config |
Performance | Very fast | Moderate | Slow on large files | Fast |
Team Adoption | Easy (minimal config) | Complex (many rules) | Moderate | Very easy |
Code Quality | Formatting only | Linting + formatting | Formatting only | Linting + formatting |
Prettier’s philosophy of being opinionated with minimal configuration options makes it ideal for teams that want to eliminate style debates. ESLint excels at code quality but requires more setup for formatting rules. The combination of Prettier for formatting and ESLint for linting has become the industry standard.
Advanced Integration Techniques
ESLint and Prettier Integration:
Install the necessary packages to prevent conflicts:
npm install --save-dev eslint-config-prettier eslint-plugin-prettier
Update your .eslintrc.js
:
module.exports = {
extends: [
'eslint:recommended',
'prettier' // Must be last to override other configs
],
plugins: ['prettier'],
rules: {
'prettier/prettier': 'error'
}
};
VS Code Workspace Settings:
Create .vscode/settings.json
for project-specific settings:
{
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true,
"source.organizeImports": true
},
"editor.formatOnSave": true,
"prettier.requireConfig": true,
"prettier.useEditorConfig": false
}
Custom Prettier Plugins:
For specialized formatting needs, install community plugins:
npm install --save-dev @trivago/prettier-plugin-sort-imports
Configure in .prettierrc
:
{
"plugins": ["@trivago/prettier-plugin-sort-imports"],
"importOrder": ["^@core/(.*)$", "^@server/(.*)$", "^@ui/(.*)$", "^[./]"],
"importOrderSeparation": true,
"importOrderSortSpecifiers": true
}
Performance Optimization and Best Practices
Prettier performance becomes critical in large codebases. Here are optimization strategies:
Selective Formatting:
Use .prettierignore
aggressively to exclude unnecessary files:
# Dependencies
node_modules/
vendor/
# Build outputs
dist/
build/
*.min.*
# Generated files
coverage/
.next/
.nuxt/
# Large data files
*.json
!package.json
!tsconfig.json
Editor Performance Settings:
{
"prettier.documentSelectors": ["**/*.{js,ts,jsx,tsx,css,scss,json,html,vue}"],
"prettier.ignorePath": ".prettierignore",
"editor.formatOnSaveMode": "modifications"
}
CI/CD Integration:
For server deployments, integrate Prettier checks in your pipeline:
# GitHub Actions example
name: Code Quality
on: [push, 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
Common Issues and Troubleshooting
Prettier Not Working:
- Verify the extension is enabled: Check Extensions panel for “Prettier – Code formatter”
- Check default formatter: Ensure
editor.defaultFormatter
is set toesbenp.prettier-vscode
- Validate configuration: Use online Prettier playground to test your
.prettierrc
syntax - Clear VS Code cache: Restart VS Code or reload the window (Ctrl+Shift+P → “Reload Window”)
Configuration Not Applied:
Prettier follows a specific configuration hierarchy. Debug with this command:
npx prettier --find-config-path ./src/index.js
Common configuration conflicts occur when:
- Multiple config files exist (package.json prettier field vs .prettierrc)
- EditorConfig settings override Prettier
- VS Code user settings conflict with workspace settings
Format on Save Issues:
If format on save isn’t working, check these settings:
{
"editor.formatOnSave": true,
"editor.defaultFormatter": "esbenp.prettier-vscode",
"[javascript]": {
"editor.formatOnSave": true
}
}
ESLint Conflicts:
When Prettier and ESLint fight over formatting rules, install compatibility packages:
npm install --save-dev eslint-config-prettier
Update ESLint config to disable conflicting rules:
module.exports = {
extends: ['eslint:recommended', 'prettier'],
rules: {
// Remove any formatting-related rules
}
};
Advanced Use Cases and Integration
Monorepo Configuration:
For complex projects with multiple packages, use root-level configuration with overrides:
{
"printWidth": 100,
"semi": true,
"singleQuote": true,
"overrides": [
{
"files": "packages/api/**/*.js",
"options": {
"printWidth": 120,
"tabWidth": 4
}
},
{
"files": "packages/frontend/**/*.{js,jsx,ts,tsx}",
"options": {
"jsxSingleQuote": true,
"bracketSameLine": true
}
}
]
}
Docker Development Environment:
For consistent formatting across development environments, including containerized setups:
FROM node:18-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run format:check
CMD ["npm", "start"]
Prettier integrates seamlessly with modern development workflows, from local development on personal machines to automated deployments on production servers. The official documentation at https://prettier.io/docs/en/ provides comprehensive configuration options and plugin information.
The VS Code integration makes Prettier incredibly accessible for developers at all levels. Whether you’re working on a simple static website or managing complex applications across multiple servers, consistent code formatting improves readability, reduces merge conflicts, and allows teams to focus on functionality rather than style debates. The minimal configuration philosophy ensures quick adoption while the extensive plugin ecosystem handles specialized formatting needs.

This article incorporates information and material from various online sources. We acknowledge and appreciate the work of all original authors, publishers, and websites. While every effort has been made to appropriately credit the source material, any unintentional oversight or omission does not constitute a copyright infringement. All trademarks, logos, and images mentioned are the property of their respective owners. If you believe that any content used in this article infringes upon your copyright, please contact us immediately for review and prompt action.
This article is intended for informational and educational purposes only and does not infringe on the rights of the copyright owners. If any copyrighted material has been used without proper credit or in violation of copyright laws, it is unintentional and we will rectify it promptly upon notification. Please note that the republishing, redistribution, or reproduction of part or all of the contents in any form is prohibited without express written permission from the author and website owner. For permissions or further inquiries, please contact us.