Prettier Documentation

website·Indexed 43 days ago

https://prettier.io

An opinionated code formatter. Includes documentation for the JavaScript API (prettier.format, prettier.check, prettier.resolveConfig), CLI flags such as --write, --check, and --ignore-unknown, configuration file setup, and integrations for editors like Visual Studio Code, Vim, Emacs, and Helix.

Tokens
25.5K
Snippets
167
Records
211
Agent score
72%

What's inside Prettier

  1. Overview of Prettier code formatter

    Prettier is an opinionated code formatter that enforces a consistent style across a codebase. It works by parsing code into an Abstract Syntax Tree (AST) and re-printing it from scratch, taking the maximum line length into account and wrapping code when necessary. It disregards original styling to ensure consistency, although some elements like empty lines and multi-line objects are preserved when practical.
  2. Understand Prettier's opinionated approach to formatting options

    Prettier is an opinionated code formatter designed to end debates over coding styles. To maintain this goal and avoid "bike-shedding," Prettier has frozen its set of configuration options. New requests for formatting-related options are no longer accepted. Existing options (such as --arrow-parens or --jsx-single-quote) are considered historical artifacts and do not justify the addition of new ones. Options are primarily maintained only for technical necessity, such as compatibility with specific environments (e.g., --trailing-comma=es5 for older JS environments or --end-of-line for CRLF management).
  3. Understand Prettier's scope and limitations

    Prettier is strictly a code printer and does not perform code transformations. Its primary goal is to handle the visual formatting (printing) of code without altering the logic or structure. Consequently, Prettier will not perform the following actions:

    • Convert between string quotes and template literals.
    • Break long string literals into multiple parts using + to fit the print width.
    • Add or remove optional curly braces {} or return statements.
    • Convert ternary operators ?: into if-else statements.
    • Sort or move imports, object keys, class members, JSX keys, or CSS properties. Sorting is considered out of scope because it is a transformation that could introduce unsafe side effects (especially with imports) and complicate correctness verification.
  4. Extend Prettier with Plugins

    Plugins allow you to add support for new languages or implement custom formatting rules in Prettier. While the core prettier package includes JavaScript and common web languages, additional languages require the installation of a specific plugin.
  5. Understand the difference between Prettier and linters

    Prettier is a formatting tool, not a rule-based linter. It reprints the entire program from scratch to ensure consistency, eliminating the need for formatting rules (e.g., max-line-length, spacing). Linters should be used for 'code-quality rules' that catch actual bugs (e.g., unused variables, implicit globals). The recommended workflow is to use Prettier for formatting and linters for catching bugs.
  6. Ignore a single block of Markdown content

    To prevent Prettier from formatting a specific block of text in a Markdown file, place the <!-- prettier-ignore --> comment immediately before the content you wish to preserve.
    <!-- prettier-ignore -->
    Do   not    format   this
  7. Escape special characters in Prettier glob patterns

    To match directories or files containing special characters (like brackets) in globs, use escaping syntaxes. The double-bracket syntax [[] is preferred because it is cross-platform compatible, whereas backslash escaping fails on Windows where backslashes are treated as path separators.
    # Recommended cross-platform syntax
    prettier "[[]my-dir]/*.js"
    
    # Alternative syntax (does not work on Windows)
    prettier "\[my-dir]/*.js"
  8. Format partially-staged files using git-format-staged

    Use git-format-staged when you need to format only the changes that have been staged in Git, without affecting unstaged changes. Unlike some other tools, it applies the formatter directly to objects in the git object database and merges changes back to the working tree.

    Key guarantees include:

    • Changes in commits are always formatted.
    • Unstaged changes are never staged during the process.
    • Unstaged changes are not formatted.
    • If conflicts occur between formatted staged changes and unstaged changes, the working tree is left untouched to prevent data loss.

    Requirements: Python v3 or v2.7 must be installed.

  9. Ensure consistent Linux-style line endings in a git repository

    To ensure a git repository only contains Linux-style line endings (LF) for files covered by Prettier, follow these steps:

    1. Set Prettier's endOfLine option to "lf" (default since v2.0.0).
    2. Configure a pre-commit hook to run Prettier.
    3. Run Prettier in your CI pipeline using the --check flag. (For Travis CI, set autocrlf to input in .travis.yml).
    4. Add * text=auto eol=lf to the .gitattributes file. Note: Windows users may need to re-clone the repo after this change to prevent git from converting LF to CRLF on checkout.
    * text=auto eol=lf
  10. Install Prettier locally

    Install Prettier as a development dependency using your preferred package manager. It is recommended to use the --save-exact (or --exact) flag to lock the version and avoid formatting changes between releases.
    # npm
    npm install --save-dev --save-exact prettier@3.9.8
    
    # yarn
    yarn add --dev --exact prettier@3.9.8
    
    # pnpm
    pnpm add --save-dev --save-exact prettier@3.9.8
    
    # bun
    bun add --dev --exact prettier@3.9.8
    
    # deno
    deno install --dev --save-exact prettier@3.9.8
  11. Configure Prettier in JetBrains IDEs

    WebStorm has built-in Prettier support. For other JetBrains IDEs (IntelliJ IDEA, PhpStorm, PyCharm), install the Prettier plugin via Preferences / Settings | Plugins. After installation, you can manually format code using the 'Reformat with Prettier' action (macOS: Opt+Shift+Cmd+P; Windows/Linux: Alt+Shift+Ctrl+P).