Zum Inhalt springen

Prettier Cheat Sheet

Overview

Prettier is an opinionated code formatter that enforces a consistent style by parsing your code and reprinting it with its own rules. It supports JavaScript, TypeScript, CSS, HTML, JSON, YAML, Markdown, GraphQL, and many other languages through plugins. Prettier removes all original formatting and ensures that all code looks the same regardless of who wrote it.

Prettier deliberately limits the number of options it exposes, favoring convention over configuration. It integrates with all major editors, can run as a pre-commit hook, and works alongside linters like ESLint. By handling formatting automatically, Prettier eliminates style debates in code reviews and lets developers focus on logic.

Installation

# Install as a dev dependency
npm install -D prettier

# Or globally
npm install -g prettier

# With yarn
yarn add -D prettier

# With pnpm
pnpm add -D prettier

Core Commands

CommandDescription
npx prettier --write .Format all files in place
npx prettier --check .Check if files are formatted (CI)
npx prettier --write "src/**/*.{ts,tsx}"Format specific file patterns
npx prettier --write file.jsFormat a single file
npx prettier --list-different .List files that need formatting
npx prettier --find-config-path file.jsShow which config file applies
npx prettier --debug-check file.jsDebug formatting issues
npx prettier --no-config --write .Format ignoring config files
npx prettier --single-quote --write .Override options via CLI
npx prettier --cache --write .Use cache for faster re-runs

Format with Stdin

# Format stdin and output to stdout
echo "const x={a:1,b:2}" | npx prettier --parser babel

# Format a file to stdout (without writing)
npx prettier src/index.ts

Configuration

Configuration File (.prettierrc)

{
  "semi": true,
  "singleQuote": true,
  "tabWidth": 2,
  "useTabs": false,
  "trailingComma": "all",
  "printWidth": 100,
  "bracketSpacing": true,
  "arrowParens": "always",
  "endOfLine": "lf",
  "jsxSingleQuote": false,
  "bracketSameLine": false,
  "quoteProps": "as-needed",
  "proseWrap": "preserve",
  "htmlWhitespaceSensitivity": "css",
  "embeddedLanguageFormatting": "auto",
  "singleAttributePerLine": false
}

JavaScript Config (.prettierrc.mjs)

// .prettierrc.mjs
export default {
  semi: true,
  singleQuote: true,
  tabWidth: 2,
  trailingComma: "all",
  printWidth: 100,
  plugins: ["prettier-plugin-tailwindcss"],
  overrides: [
    {
      files: "*.md",
      options: {
        proseWrap: "always",
        printWidth: 80,
      },
    },
    {
      files: ["*.json", "*.yaml", "*.yml"],
      options: {
        tabWidth: 2,
      },
    },
    {
      files: "*.css",
      options: {
        singleQuote: false,
      },
    },
  ],
}

All Options

OptionDefaultDescription
printWidth80Line width before wrapping
tabWidth2Spaces per indentation level
useTabsfalseUse tabs instead of spaces
semitrueAdd semicolons at end of statements
singleQuotefalseUse single quotes
quoteProps"as-needed"Quote object properties: as-needed, consistent, preserve
jsxSingleQuotefalseUse single quotes in JSX
trailingComma"all"Trailing commas: all, es5, none
bracketSpacingtrueSpaces inside object braces
bracketSameLinefalsePut > on same line in HTML/JSX
arrowParens"always"Parens around single arrow fn param: always, avoid
proseWrap"preserve"Markdown wrapping: always, never, preserve
htmlWhitespaceSensitivity"css"HTML whitespace: css, strict, ignore
endOfLine"lf"Line endings: lf, crlf, cr, auto
singleAttributePerLinefalseOne attribute per line in HTML/JSX

Ignore File (.prettierignore)

# .prettierignore
dist/
build/
coverage/
node_modules/
*.min.js
*.min.css
package-lock.json
yarn.lock
pnpm-lock.yaml
.env
.env.*

Editor Integration

VS Code

// .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"
  },
  "[css]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  }
}

Advanced Usage

Pre-Commit Hook with Husky

# Install husky and lint-staged
npm install -D husky lint-staged
npx husky init

# Configure lint-staged
cat > .lintstagedrc.json << 'EOF'
{
  "*.{js,ts,tsx,jsx}": ["prettier --write", "eslint --fix"],
  "*.{css,scss}": "prettier --write",
  "*.{json,yaml,yml,md}": "prettier --write"
}
EOF

# Add to husky pre-commit hook
echo "npx lint-staged" > .husky/pre-commit

ESLint Integration

# Install eslint-config-prettier to avoid conflicts
npm install -D eslint-config-prettier
// eslint.config.js
import prettier from "eslint-config-prettier"

export default [
  // ... your other configs
  prettier, // Must be LAST to disable conflicting rules
]

Plugins

# Tailwind CSS class sorting
npm install -D prettier-plugin-tailwindcss

# Sort imports
npm install -D @trivago/prettier-plugin-sort-imports

# PHP
npm install -D @prettier/plugin-php

# XML
npm install -D @prettier/plugin-xml

# TOML
npm install -D prettier-plugin-toml
// .prettierrc with plugins
{
  "plugins": [
    "@trivago/prettier-plugin-sort-imports",
    "prettier-plugin-tailwindcss"
  ],
  "importOrder": [
    "^react",
    "^@/(.*)$",
    "^[./]"
  ],
  "importOrderSeparation": true,
  "importOrderSortSpecifiers": true
}

CI/CD Check

# .github/workflows/format.yml
name: Check Formatting
on: [push, pull_request]
jobs:
  prettier:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: 20
      - run: npm ci
      - run: npx prettier --check .

Ignore Specific Code

// prettier-ignore
const matrix = [
  1, 0, 0,
  0, 1, 0,
  0, 0, 1,
]

// For a range of code:
// prettier-ignore-start
const ugly = {a:1,    b:2,      c:3}
// prettier-ignore-end
<!-- prettier-ignore -->
<div class="special"   id="keep-this"   data-value="as-is"></div>
/* prettier-ignore */
.class { color: red;     background: blue;     margin: 0; }

Troubleshooting

IssueSolution
Formatting conflicts with ESLintInstall eslint-config-prettier and add it as the last ESLint config
Wrong parser usedSpecify parser explicitly: --parser typescript or set in config overrides
Plugin not workingEnsure plugin is in plugins array in config; restart editor
Slow on large projectsUse --cache flag; add large directories to .prettierignore
Format on save not workingCheck VS Code default formatter is set to Prettier; check Output panel
Trailing comma errorsSet "trailingComma": "es5" or "all" depending on target
End of line differencesSet "endOfLine": "lf" and configure Git: git config core.autocrlf input
Config not detectedRun npx prettier --find-config-path file.js to debug config resolution
Different results locally vs CIEnsure same Prettier version; pin in package.json