Prettier Complete Guide | Opinionated Code Formatter

Prettier Complete Guide | Opinionated Code Formatter

이 글의 핵심

Prettier is an opinionated code formatter that enforces consistent style. It supports JavaScript, TypeScript, CSS, HTML, JSON, and more with zero configuration.

Introduction

Prettier is an opinionated code formatter that removes all original styling and ensures consistent code style. It takes your code and reprints it according to its own rules.

Before Prettier

// Developer A
function   add(a,b){return a+b}

// Developer B
function add( a , b ) {
  return a + b
}

// Developer C
function add(a, b) { return a + b; }

After Prettier

// Everyone
function add(a, b) {
  return a + b;
}

1. Installation

npm install --save-dev prettier

Quick Start

# Format all files
npx prettier --write .

# Check formatting
npx prettier --check .

# Format specific files
npx prettier --write "src/**/*.{js,jsx,ts,tsx}"

2. Configuration

.prettierrc

{
  "semi": true,
  "trailingComma": "es5",
  "singleQuote": true,
  "printWidth": 80,
  "tabWidth": 2,
  "useTabs": false,
  "arrowParens": "always",
  "endOfLine": "lf"
}

.prettierignore

# .prettierignore
node_modules
dist
build
coverage
.next
.cache
*.min.js
package-lock.json
yarn.lock
pnpm-lock.yaml

3. IDE Integration

VS Code

# Install extension
code --install-extension esbenp.prettier-vscode

settings.json:

{
  "editor.defaultFormatter": "esbenp.prettier-vscode",
  "editor.formatOnSave": true,
  "[javascript]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
  "[typescript]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  }
}

WebStorm

Settings → Languages & Frameworks → JavaScript → Prettier

  • ✅ Enable “On save”
  • ✅ Enable “On code reformat”

4. Pre-commit Hook

With Husky + lint-staged

npm install --save-dev husky lint-staged
npx husky init

package.json:

{
  "lint-staged": {
    "*.{js,jsx,ts,tsx,css,md,json}": "prettier --write"
  }
}

.husky/pre-commit:

npx lint-staged

Now Prettier runs automatically before commit!

5. ESLint Integration

npm install --save-dev eslint-config-prettier eslint-plugin-prettier

.eslintrc.json:

{
  "extends": [
    "eslint:recommended",
    "plugin:prettier/recommended"
  ],
  "plugins": ["prettier"],
  "rules": {
    "prettier/prettier": "error"
  }
}

Now ESLint shows Prettier errors!

6. Configuration Options

{
  "printWidth": 80,              // Line length
  "tabWidth": 2,                 // Spaces per tab
  "useTabs": false,              // Use spaces, not tabs
  "semi": true,                  // Add semicolons
  "singleQuote": true,           // Use single quotes
  "quoteProps": "as-needed",     // Quote object keys only when needed
  "jsxSingleQuote": false,       // Use double quotes in JSX
  "trailingComma": "es5",        // Trailing commas where valid in ES5
  "bracketSpacing": true,        // Spaces in object literals
  "bracketSameLine": false,      // JSX bracket on next line
  "arrowParens": "always",       // Always parens around arrow function args
  "endOfLine": "lf"              // Unix line endings
}
{
  "singleQuote": true,
  "trailingComma": "es5"
}

Let Prettier handle the rest!

7. Language Support

Prettier supports many languages:

prettier --write "**/*.{js,jsx,ts,tsx,json,css,scss,md,html,yaml,yml}"

JavaScript/TypeScript

// Before
const obj={a:1,b:2,c:3};

// After
const obj = { a: 1, b: 2, c: 3 };

React/JSX

// Before
<Button onClick={()=>console.log('clicked')} disabled={true} />

// After
<Button onClick={() => console.log('clicked')} disabled />

CSS

/* Before */
.button{background:blue;color:white}

/* After */
.button {
  background: blue;
  color: white;
}

JSON

{"name":"my-app","version":"1.0.0","dependencies":{"react":"^18.0.0"}}
{
  "name": "my-app",
  "version": "1.0.0",
  "dependencies": {
    "react": "^18.0.0"
  }
}

8. CI/CD Integration

GitHub Actions

name: Format Check

on: [push, pull_request]

jobs:
  format:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - uses: actions/setup-node@v3
        with:
          node-version: 18
      - run: npm ci
      - run: npx prettier --check .

Auto-fix on PR

- name: Run Prettier
  run: |
    npx prettier --write .
    git config user.name github-actions
    git config user.email github-actions@github.com
    git add .
    git diff --quiet && git diff --staged --quiet || git commit -m "style: format code with Prettier"
    git push

9. Team Workflow

1. Add to Project

npm install --save-dev prettier

2. Create Config

// .prettierrc
{
  "singleQuote": true,
  "trailingComma": "es5"
}

3. Format Everything

npx prettier --write .
git add .
git commit -m "style: format codebase with Prettier"

4. Setup Pre-commit Hook

npm install --save-dev husky lint-staged
npx husky init

5. Add to CI

# .github/workflows/format.yml
- run: npx prettier --check .

10. Best Practices

1. Minimal Configuration

{
  "singleQuote": true
}

Trust Prettier’s defaults!

2. Format on Save

Enable in your IDE for instant feedback.

3. Use with ESLint

npm install --save-dev eslint-config-prettier

4. Ignore Generated Files

# .prettierignore
dist/
build/
*.min.js

11. Common Issues

Problem: Conflicts with ESLint

Solution: Use eslint-config-prettier

npm install --save-dev eslint-config-prettier
{
  "extends": ["eslint:recommended", "prettier"]
}

Problem: Different formatting in CI vs local

Solution: Pin Prettier version

{
  "devDependencies": {
    "prettier": "3.2.5"
  }
}

Summary

Prettier eliminates code style debates:

  • Opinionated - minimal configuration
  • Consistent - same output every time
  • Fast - formats entire codebase in seconds
  • Multi-language - JS, TS, CSS, HTML, and more
  • Editor integration for all major IDEs

Key Takeaways:

  1. Zero config code formatting
  2. Integrates with ESLint
  3. Use pre-commit hooks
  4. Format on save in IDE
  5. Enforces team consistency

Next Steps:

Resources: