← Recipes

阅读中文版本

Keep Formatting Deterministic with Prettier

Run Prettier as the single formatting authority, add ignore files for generated output, and enforce it in CI so diffs never mix formatting with logic.

~25 minprettiertoolingdx

Task

Establish Prettier as the only formatter and enforce it so reviews stay about logic.

When to use this

Formatting is a mix of editor settings and arguments, so every PR contains whitespace churn that hides real changes.

Prerequisites

  • Prettier installed
  • A CI step that can fail on unformatted files

Steps

1. Configure Prettier once at the repo root and remove competing formatters.

Expected output: There is one formatting authority.

2. Add .prettierignore for build output, generated files, and vendored code.

Expected output: Generated files are never reformatted.

3. Run prettier --check in CI and fail on drift.

Expected output: Formatting cannot regress.

4. Integrate with the editor so files format on save.

npx prettier --check .

Expected output: Developers rarely produce drift to fix.

Troubleshooting

Problem

Check fails on a generated file

Solution

Add it to .prettierignore; do not hand-format generated code.

Problem

Conflicts with ESLint stylistic rules

Solution

Disable stylistic ESLint rules and let Prettier own formatting; run eslint-config-prettier.

Limitations

  • Prettier has opinions that do not suit every codebase, so adopting it means accepting its output style.
  • A repo-wide format change creates a large diff that should be isolated from logic changes.

Context

Establish Prettier as the only formatter and enforce it so reviews stay about logic. Formatting is a mix of editor settings and arguments, so every PR contains whitespace churn that hides real changes.

Steps

  1. Configure Prettier once at the repo root and remove competing formatters. Expected: There is one formatting authority.
  2. Add .prettierignore for build output, generated files, and vendored code. Expected: Generated files are never reformatted.
  3. Run prettier –check in CI and fail on drift. Expected: Formatting cannot regress.
  4. Integrate with the editor so files format on save. Expected: Developers rarely produce drift to fix.
npx prettier --check .
npx prettier --write .
# .prettierignore
dist
coverage
*.generated.ts

Verify

  • There is one formatting authority.
  • Generated files are never reformatted.
  • Formatting cannot regress.
  • Developers rarely produce drift to fix.

Limits

  • Prettier has opinions that do not suit every codebase, so adopting it means accepting its output style.
  • A repo-wide format change creates a large diff that should be isolated from logic changes.