DevToolBoxGRATIS
Blog

Guía Completa de Prettier: Formateo de Código Consistente

20 min readpor DevToolBox Team

Prettier is the most widely adopted opinionated code formatter for JavaScript, TypeScript, HTML, CSS, JSON, Markdown, and many other languages. It enforces a consistent code style by parsing your code and reprinting it with its own rules, eliminating debates about formatting in code reviews. With over 50 million weekly npm downloads, Prettier has become an essential part of the modern development toolchain. This guide covers everything from basic setup and configuration to advanced topics like ESLint integration, editor plugins, pre-commit hooks, CI/CD enforcement, custom plugins, and the philosophy behind opinionated formatting.

TL;DR

Prettier is an opinionated code formatter that supports 20+ languages including JavaScript, TypeScript, CSS, HTML, JSON, and Markdown. Configure it via .prettierrc with options like printWidth, tabWidth, singleQuote, and trailingComma. Integrate with ESLint using eslint-config-prettier, set up pre-commit hooks with lint-staged and husky, and enforce formatting in CI/CD. Prettier deliberately limits configuration options to end style debates and keep teams focused on writing code.

Key Takeaways
  • Prettier formats code by parsing it into an AST and reprinting it, guaranteeing consistent output regardless of the original formatting.
  • The .prettierrc file supports JSON, YAML, TOML, JS, and TS formats with options like printWidth (80), tabWidth (2), singleQuote, and trailingComma.
  • Use eslint-config-prettier to disable ESLint formatting rules that conflict with Prettier, keeping ESLint for code quality only.
  • Pre-commit hooks with husky and lint-staged ensure every commit is formatted before it reaches the repository.
  • CI/CD pipelines should run prettier --check to catch unformatted code without modifying files.
  • Prettier plugins extend language support to Tailwind CSS class sorting, SQL, PHP, Java, XML, TOML, and more.

What Is Prettier and Why Use It?

Prettier is an opinionated code formatter that removes all original styling and ensures that all outputted code conforms to a consistent style. Unlike linters that report problems for you to fix, Prettier takes your code, parses it into an abstract syntax tree (AST), and reprints it from scratch according to its formatting rules. The result is deterministic: the same code always produces the same output regardless of the original formatting.

The key insight behind Prettier is that arguing about code formatting is a waste of time. By adopting an opinionated formatter with minimal configuration options, teams eliminate style debates in code reviews and free up mental energy for logic, architecture, and design decisions. Prettier supports JavaScript, TypeScript, JSX, TSX, CSS, Less, SCSS, HTML, JSON, GraphQL, Markdown, YAML, and more through its plugin system.

Prettier differs from traditional formatters because it considers the entire program structure when making formatting decisions. It understands line length budgets and will break long lines into multiple lines, respecting language-specific syntax rules. A simple property access that fits on one line stays on one line, but the same expression with a longer chain will be broken across multiple lines automatically.

Installing and Setting Up Prettier

Prettier can be installed as a project dependency or used globally. The recommended approach is to install it as a devDependency in each project so that all team members use the same version.

# Install Prettier as a dev dependency
npm install --save-dev prettier

# Or with yarn
yarn add --dev prettier

# Or with pnpm
pnpm add --save-dev prettier

# Or with bun
bun add --dev prettier

After installation, you can run Prettier from the command line. The most common commands are formatting files in place, checking if files are formatted, and formatting specific file types.

# Format all files in the current directory
npx prettier --write .

# Check if files are formatted (no changes made)
npx prettier --check .

# Format specific file types
npx prettier --write "src/**/*.{ts,tsx,js,jsx}"
npx prettier --write "**/*.{css,scss,less}"
npx prettier --write "**/*.{json,md,yaml,yml}"

# Format a single file
npx prettier --write src/app.tsx

# Output formatted code to stdout (no file changes)
npx prettier src/app.tsx

Configuration with .prettierrc

Prettier is designed to work with minimal configuration. However, it does provide a set of options that you can customize to match your team preferences. Configuration can be specified in several file formats: .prettierrc (JSON or YAML), .prettierrc.json, .prettierrc.yml, .prettierrc.toml, .prettierrc.js, .prettierrc.cjs, .prettierrc.mjs, or a prettier key in package.json.

Here are the most commonly used Prettier options and their default values. Most teams only need to change 3 to 5 of these options.

// .prettierrc (JSON format - most common)
{
  "printWidth": 100,
  "tabWidth": 2,
  "useTabs": false,
  "semi": true,
  "singleQuote": true,
  "trailingComma": "all",
  "bracketSpacing": true,
  "arrowParens": "always",
  "endOfLine": "lf"
}
# .prettierrc (YAML format)
printWidth: 100
tabWidth: 2
useTabs: false
semi: true
singleQuote: true
trailingComma: all
bracketSpacing: true
arrowParens: always
endOfLine: lf
// prettier.config.mjs (ES module format)
/** @type {import("prettier").Config} */
const config = {
  printWidth: 100,
  tabWidth: 2,
  singleQuote: true,
  trailingComma: "all",
  arrowParens: "always",
  plugins: ["prettier-plugin-tailwindcss"],
};

export default config;

Complete Options Reference

OptionDefaultDescription
printWidth80Line length that the printer will try to wrap at. Not a hard limit.
tabWidth2Number of spaces per indentation level.
useTabsfalseUse tabs instead of spaces for indentation.
semitrueAdd semicolons at the end of statements.
singleQuotefalseUse single quotes instead of double quotes.
trailingComma"all"Trailing commas where valid in ES5+ (objects, arrays, etc.).
bracketSpacingtrueSpaces between brackets in object literals: { foo: bar }.
arrowParens"always"Parentheses around a sole arrow function parameter: (x) => x.
endOfLine"lf"Line ending style: lf, crlf, cr, or auto.
jsxSingleQuotefalseUse single quotes in JSX attributes.
bracketSameLinefalsePut the closing > of a multi-line JSX element on the last line.
proseWrap"preserve"How to wrap Markdown text: always, never, or preserve.

Ignoring Files with .prettierignore

The .prettierignore file works exactly like .gitignore and uses the same syntax. It tells Prettier which files and directories to skip. By default, Prettier ignores files in node_modules and common version control directories. You should also ignore build output, generated files, and any files managed by other tools.

# .prettierignore

# Build output
dist/
build/
.next/
out/

# Dependencies
node_modules/

# Lock files
package-lock.json
yarn.lock
pnpm-lock.yaml

# Generated files
*.min.js
*.min.css
*.generated.*
coverage/

# Environment files
.env
.env.*

# Public assets
public/
static/

You can also ignore specific lines or blocks within a file using special comments. This is useful for code that must maintain a specific format, such as ASCII art tables, alignment-dependent code, or generated content.

// prettier-ignore - ignores the next node
const matrix = [
  // prettier-ignore
  [1, 0, 0,
   0, 1, 0,
   0, 0, 1],
];

/* In HTML: */
<!-- prettier-ignore -->
<div   class="custom-alignment"   data-value="keep"  >
  Content here
</div>

/* In CSS: */
/* prettier-ignore */
.my-class    { color:   red; }

/* In Markdown: */
<!-- prettier-ignore-start -->
| Column 1    | Column 2    | Column 3    |
| ----------- | ----------- | ----------- |
| Aligned     | Content     | Here        |
<!-- prettier-ignore-end -->

Integration with ESLint

Prettier and ESLint serve different purposes. ESLint catches code quality issues (unused variables, missing error handling, incorrect types) while Prettier handles formatting (indentation, line breaks, quotes, semicolons). The challenge is that ESLint also has formatting rules that can conflict with Prettier. The solution is eslint-config-prettier, which disables all ESLint rules that are unnecessary or might conflict with Prettier.

The recommended setup in 2026 uses ESLint flat config with eslint-config-prettier. This ensures ESLint handles code quality while Prettier handles formatting, with no conflicts between them.

# Install eslint-config-prettier
npm install --save-dev eslint-config-prettier
// eslint.config.js - ESLint + Prettier (flat config)
import js from "@eslint/js";
import tseslint from "typescript-eslint";
import prettierConfig from "eslint-config-prettier";

export default [
  js.configs.recommended,
  ...tseslint.configs.recommended,

  // Custom code quality rules
  {
    rules: {
      "no-unused-vars": "warn",
      "prefer-const": "error",
      "no-console": ["error", { allow: ["warn", "error"] }],
    },
  },

  // MUST be last: disables formatting rules that conflict with Prettier
  prettierConfig,
];

Some teams previously used eslint-plugin-prettier which ran Prettier as an ESLint rule. This approach is now discouraged because it is slower (Prettier runs inside ESLint), produces noisy ESLint output for formatting issues, and creates confusing error messages. The recommended approach is to run ESLint and Prettier as separate tools.

// package.json - Run ESLint and Prettier as separate scripts
{
  "scripts": {
    "lint": "eslint src/",
    "lint:fix": "eslint --fix src/",
    "format": "prettier --write .",
    "format:check": "prettier --check .",
    "check": "npm run lint && npm run format:check"
  }
}

Editor Integration

Prettier integrates with all major code editors. Format-on-save is the most productive workflow: every time you save a file, Prettier automatically formats it. This eliminates the need to think about formatting while coding and ensures every saved file is properly formatted.

VS Code

The Prettier VS Code extension is the most popular Prettier editor integration with over 40 million installs. Install it from the VS Code marketplace and configure format-on-save in your settings.

// .vscode/settings.json
{
  // Set Prettier as the default formatter
  "editor.defaultFormatter": "esbenp.prettier-vscode",

  // Format on save
  "editor.formatOnSave": true,

  // Per-language formatter overrides
  "[javascript]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
  "[typescript]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
  "[typescriptreact]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
  "[json]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
  "[css]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
  "[html]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
  "[markdown]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  }
}

JetBrains IDEs (WebStorm, IntelliJ)

JetBrains IDEs have built-in Prettier support. Enable it in Settings > Languages & Frameworks > JavaScript > Prettier. Check the boxes for On Save and On Reformat Code to automatically format with Prettier.

// JetBrains Prettier settings path:
// Settings > Languages & Frameworks > JavaScript > Prettier
//
// Configuration:
// - Prettier package: ~/project/node_modules/prettier
// - Run for files: **/*.{js,ts,jsx,tsx,css,scss,json,md,yaml,yml,html}
// - [x] On Save
// - [x] On Reformat Code (Ctrl+Alt+L / Cmd+Opt+L)

Vim / Neovim

For Vim and Neovim, use the neoformat plugin or the built-in formatprg option. With neoformat, you can configure format-on-save in your configuration file.

-- Neovim with conform.nvim (recommended)
-- ~/.config/nvim/lua/plugins/formatting.lua
return {
  "stevearc/conform.nvim",
  opts = {
    formatters_by_ft = {
      javascript = { "prettier" },
      typescript = { "prettier" },
      typescriptreact = { "prettier" },
      css = { "prettier" },
      html = { "prettier" },
      json = { "prettier" },
      yaml = { "prettier" },
      markdown = { "prettier" },
    },
    format_on_save = {
      timeout_ms = 3000,
      lsp_fallback = true,
    },
  },
}

Pre-commit Hooks with Husky and lint-staged

Editor integration catches most formatting issues during development, but pre-commit hooks provide a safety net. They ensure that every commit in the repository is properly formatted, regardless of which editor or IDE each developer uses. The standard approach uses husky for Git hooks and lint-staged to run Prettier only on staged files.

# Step 1: Install husky and lint-staged
npm install --save-dev husky lint-staged

# Step 2: Initialize husky
npx husky init

# Step 3: Update the pre-commit hook
echo "npx lint-staged" > .husky/pre-commit
// package.json - lint-staged configuration
{
  "lint-staged": {
    "*.{js,jsx,ts,tsx}": [
      "prettier --write",
      "eslint --fix"
    ],
    "*.{css,scss,less}": [
      "prettier --write"
    ],
    "*.{json,md,yaml,yml,html}": [
      "prettier --write"
    ]
  }
}

This setup runs Prettier on every staged file that matches the specified patterns. If Prettier changes a file, lint-staged automatically adds the change to the commit. This means developers never see formatting diffs in their pull requests because files are always formatted before they enter the repository.

CI/CD Pipeline Integration

While pre-commit hooks catch most formatting issues locally, CI/CD provides the final enforcement layer. The prettier --check command verifies that all files are formatted without modifying them. If any file is not formatted, the command exits with a non-zero code, failing the CI pipeline.

# .github/workflows/format-check.yml
name: Format Check

on:
  push:
    branches: [main]
  pull_request:
    branches: [main]

jobs:
  format:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - uses: actions/setup-node@v4
        with:
          node-version: 22
          cache: npm

      - run: npm ci

      - name: Check formatting
        run: npx prettier --check .

      - name: Run ESLint
        run: npx eslint src/

Running Prettier in CI ensures that even if a developer bypasses pre-commit hooks (with git commit --no-verify), the formatting requirement is still enforced before code is merged.

# GitLab CI - .gitlab-ci.yml
format-check:
  stage: test
  image: node:22
  cache:
    paths:
      - node_modules/
  script:
    - npm ci
    - npx prettier --check .
    - npx eslint src/

Prettier Plugins

Prettier has a plugin system that extends its language support and capabilities. Plugins can add new languages, modify existing formatting behavior, or add entirely new features. Some of the most popular community plugins include Tailwind CSS class sorting, SQL formatting, PHP formatting, and XML formatting.

# Install popular Prettier plugins

# Tailwind CSS - sorts Tailwind classes automatically
npm install --save-dev prettier-plugin-tailwindcss

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

# PHP formatting
npm install --save-dev @prettier/plugin-php

# XML formatting
npm install --save-dev @prettier/plugin-xml

# SQL formatting
npm install --save-dev prettier-plugin-sql

Plugins are installed as npm packages and can be configured in your .prettierrc file using the plugins array. Prettier automatically loads plugins listed in this array.

// .prettierrc - with plugins configured
{
  "printWidth": 100,
  "singleQuote": true,
  "trailingComma": "all",
  "plugins": [
    "prettier-plugin-tailwindcss",
    "@trivago/prettier-plugin-sort-imports"
  ],
  "importOrder": [
    "^react",
    "^next",
    "<THIRD_PARTY_MODULES>",
    "^@/(.*)$",
    "^[./]"
  ],
  "importOrderSeparation": true,
  "importOrderSortSpecifiers": true
}

The Opinionated Formatting Philosophy

Prettier deliberately provides very few configuration options compared to other formatters. This is not a limitation but a core design decision. The Prettier team has observed that more options lead to more debates, more inconsistency, and more time spent on configuration instead of writing code.

When a team adopts Prettier, they agree to accept its decisions. The initial adjustment period is brief: most developers stop noticing the formatting after a few days. The benefit is permanent: no more bike-shedding about whether to use tabs or spaces, where to put brackets, or how to align object properties.

  • Fewer options means less time configuring and more time coding.
  • Consistent formatting across all files in a project, regardless of who wrote them.
  • No formatting discussions in code reviews, allowing focus on logic and architecture.
  • New team members can start coding immediately without learning a style guide.
  • Cross-project consistency when multiple projects use the same minimal Prettier config.

Per-File and Per-Language Overrides

Prettier allows you to apply different configuration options to specific files or file types using the overrides field in .prettierrc. This is useful when different parts of your project need different formatting rules, such as wider print widths for HTML files or different quote styles for JSON.

// .prettierrc - with per-file overrides
{
  "printWidth": 80,
  "singleQuote": true,
  "trailingComma": "all",
  "overrides": [
    {
      "files": "*.html",
      "options": {
        "printWidth": 120
      }
    },
    {
      "files": "*.md",
      "options": {
        "proseWrap": "always",
        "printWidth": 80
      }
    },
    {
      "files": ["*.json", "*.jsonc"],
      "options": {
        "tabWidth": 4
      }
    },
    {
      "files": "*.css",
      "options": {
        "singleQuote": false
      }
    }
  ]
}

Prettier vs Other Formatters

Understanding how Prettier compares to other formatting tools helps you choose the right tool for your project.

FeaturePrettierBiomedprint
SpeedFast (JavaScript)Very fast (Rust)Very fast (Rust)
Language support20+ (with plugins)JS/TS/JSON/CSSJS/TS/JSON/Markdown
Plugin ecosystemLargeNoneSmall
ConfigurationMinimal (opinionated)More optionsMore options
Editor supportExcellentGoodGood
AdoptionIndustry standardGrowing rapidlyNiche

Prettier remains the industry standard in 2026 due to its broad language support, plugin ecosystem, and universal editor integration. Biome is a compelling alternative for teams that only need JavaScript and TypeScript formatting and want maximum speed. dprint is another Rust-based option with configurable formatting rules.

Migrating a Project to Prettier

Adopting Prettier in an existing project requires a one-time formatting commit that touches many files. The recommended approach is to format the entire codebase in a single commit, then configure pre-commit hooks and CI/CD to maintain formatting going forward.

# Step 1: Install Prettier
npm install --save-dev prettier

# Step 2: Create minimal config
echo '{ "singleQuote": true, "trailingComma": "all" }' > .prettierrc

# Step 3: Create .prettierignore
echo "dist/\nbuild/\nnode_modules/\npackage-lock.json" > .prettierignore

# Step 4: Format entire codebase
npx prettier --write .

# Step 5: Commit the formatting change
git add -A
git commit -m "style: format codebase with Prettier"

To make the migration commit less disruptive in git blame, configure git to ignore the formatting commit using a .git-blame-ignore-revs file. GitHub and many other Git hosts support this file format natively.

# .git-blame-ignore-revs
# Prettier initial formatting
abc123def456789...

# Tell git to use this file
git config blame.ignoreRevsFile .git-blame-ignore-revs

# GitHub automatically reads .git-blame-ignore-revs
# so the formatting commit is hidden in blame views

Best Practices

Follow these recommendations to get the most value from Prettier in your project.

  • Install Prettier as a devDependency in every project rather than relying on global installations to ensure version consistency.
  • Keep your .prettierrc minimal. The fewer options you customize, the closer you stay to the community standard.
  • Use format-on-save in your editor. This is the single most impactful workflow improvement Prettier offers.
  • Set up pre-commit hooks with husky and lint-staged as a safety net for commits from any environment.
  • Add prettier --check to your CI/CD pipeline as the final formatting enforcement layer.
  • Use .prettierignore to skip generated files, build output, and third-party code that should not be reformatted.
  • When migrating an existing project, format everything in one commit and add it to .git-blame-ignore-revs.
  • Run Prettier and ESLint as separate tools. Do not use eslint-plugin-prettier to run Prettier inside ESLint.
  • Pin your Prettier version in package.json to avoid unexpected formatting changes when a new version is released.
  • Use the overrides field in .prettierrc for files that need different formatting rules instead of disabling Prettier entirely.

Frequently Asked Questions

What is Prettier and what does it do?

Prettier is an opinionated code formatter that supports JavaScript, TypeScript, CSS, HTML, JSON, Markdown, and many other languages through plugins. It parses your code into an AST and reprints it with consistent formatting, eliminating style debates in code reviews and ensuring uniform code style across your entire project.

How do I configure Prettier?

Create a .prettierrc file in your project root with JSON or YAML configuration. Common options include printWidth (default 80), tabWidth (default 2), singleQuote (default false), semi (default true), and trailingComma (default "all"). Most teams only need to change 3 to 5 options from the defaults.

How do I use Prettier with ESLint?

Install eslint-config-prettier and add it as the last item in your ESLint config to disable all formatting rules that conflict with Prettier. Run ESLint for code quality rules and Prettier for formatting as separate tools. Do not use eslint-plugin-prettier as it is slower and produces noisy output.

How do I set up Prettier pre-commit hooks?

Install husky and lint-staged as devDependencies. Run npx husky init to create the .husky directory. Add a pre-commit hook that runs npx lint-staged. Configure lint-staged in package.json to run prettier --write on staged files matching your file patterns.

How do I run Prettier in CI/CD?

Add npx prettier --check . to your CI/CD pipeline. The --check flag verifies formatting without modifying files and exits with a non-zero code if any file is not formatted. This fails the pipeline and prevents unformatted code from being merged.

What files should I ignore with Prettier?

Create a .prettierignore file with patterns for build output (dist/, build/, .next/), dependencies (node_modules/), generated files (*.min.js, *.generated.*), lock files (package-lock.json, yarn.lock, pnpm-lock.yaml), and any third-party code that should not be reformatted.

What is the difference between Prettier and Biome?

Prettier is a JavaScript-based formatter with broad language support (20+ languages via plugins) and is the industry standard. Biome is a Rust-based toolchain that combines formatting and linting in one faster binary but supports fewer languages (JS, TS, JSON, CSS). Choose Prettier for broad language support and plugin ecosystem, Biome for maximum speed in JavaScript and TypeScript projects.

How do I format only changed files with Prettier?

Use lint-staged with pre-commit hooks to format only staged files. For manual formatting of changed files, you can pipe git diff output to Prettier: git diff --name-only --diff-filter=ACMR | xargs npx prettier --write. In CI, use prettier --check with the list of changed files from your pull request.

𝕏 Twitterin LinkedIn
¿Fue útil?

Mantente actualizado

Recibe consejos de desarrollo y nuevas herramientas.

Sin spam. Cancela cuando quieras.

Prueba estas herramientas relacionadas

{ }JSON FormatterH↓HTML Minifier Online

Artículos relacionados

Guía ESLint 9 2026: Flat Config, TypeScript y Linting Moderno

Guía completa de ESLint: flat config, reglas, TypeScript-ESLint, plugins React/Vue, reglas personalizadas, configs compartibles, integración IDE y auto-fix.

Guía Vitest 2026: Pruebas Unitarias Rápidas para JavaScript y TypeScript Moderno

Guía completa de Vitest: configuración, sintaxis de test, mocking, pruebas de snapshot, cobertura de código, pruebas de componentes Vue/React, integración TypeScript.

TypeScript Type Guards: Guía Completa de Verificación de Tipos

Domina type guards en TypeScript: typeof, instanceof, in y guards personalizados.