Sub topic 8
Installing and Running Prettier
Prettier is an opinionated code formatter. It ignores how your code is laid out, parses it, and prints it again in one consistent style. This chapter covers installing Prettier, running it from the command line, and reading its output and exit codes. Configuration options, ignore rules, and the ESLint integration each get their own chapter later.
This chapter assumes you can run Node.js and npm from a terminal, edit package.json, and read modern JavaScript.
How Prettier Works Internally
Knowing what Prettier does under the hood explains most of its behavior, including the things it refuses to do.
- Prettier picks a parser from the file extension:
.jsuses Babel,.tsuses TypeScript,.cssuses PostCSS, and so on. - The parser turns your source into an abstract syntax tree (AST), a data structure that records what the code means and drops how it was laid out.
- A printer walks the AST and builds an intermediate "Doc," which describes groups of code that can stay on one line or break across several.
- The line-fitting algorithm keeps each group on one line if it fits within
printWidth(80 by default), and breaks it if it does not.
Your original whitespace, line breaks, and quote style are thrown away in step 2, so nearly every layout choice you made is ignored. The main exception: Prettier keeps an object literal expanded if you put a newline between { and the first key. If your file cannot be parsed, Prettier stops with a syntax error and leaves the file unchanged.
Installing Prettier
Install Prettier as a local development dependency and pin the exact version:
npm install --save-dev --save-exact prettierThe --save-exact flag writes "prettier": "3.3.3" (or whichever version you got) instead of "^3.3.3". Prettier's maintainers recommend this because even patch releases can change output slightly. With a caret range, two developers, or a developer and CI, can end up on different versions and reformat each other's files back and forth.
Next, create an empty config file. Its contents come in the next chapter, but its presence matters now: editor extensions and other tools look for a config file to tell that a project uses Prettier.
node --eval "require('fs').writeFileSync('.prettierrc', '{}\n')"This one-liner works the same in bash, zsh, PowerShell, and cmd. Some echo commands on Windows write the file in UTF-16, and Prettier cannot parse that.
Running Prettier on a File
Create src/greet.js with some deliberately messy layout:
const user = {name:'Ada',
roles : ['admin','editor'] }
function greet( u ){return 'Hello, '+u.name}
console.log(greet(user))Print the formatted result to the terminal without changing the file:
npx prettier src/greet.jsThe output uses Prettier's defaults: double quotes, semicolons, two-space indentation, and 80 columns:
const user = { name: "Ada", roles: ["admin", "editor"] };
function greet(u) {
return "Hello, " + u.name;
}
console.log(greet(user));The object collapsed onto one line because there was no newline right after { and the result fits in 80 columns. If you edit the source to put a line break after {, Prettier keeps the object expanded with one property per line.
The Three Run Modes
Prettier has three modes, and each one fits a different job.
| Command | What it does | Modifies files | Typical use |
|---|---|---|---|
| `npx prettier <paths>` | Prints formatted code to stdout | No | Previewing a single file |
| `npx prettier <paths> --write` | Rewrites files in place | Yes | Local formatting |
| `npx prettier <paths> --check` | Reports unformatted files | No | CI and verification |
| `npx prettier <paths> --list-different` | Prints only the paths of unformatted files | No | Scripting |
To format the whole project, pass . as the path:
npx prettier . --writePrettier finds every file it has a parser for, including JavaScript, TypeScript, JSON, CSS, Markdown, YAML, and HTML. It skips files it does not recognize when you pass a directory or glob. It skips node_modules by default, and in Prettier 3 it also skips anything listed in .gitignore or .prettierignore.
Running --check on the messy file before fixing it looks like this:
npx prettier . --checkChecking formatting...
[warn] src/greet.js
[warn] Code style issues found in the above file. Run Prettier with --write to fix.Exit Codes
Scripts and CI decide pass or fail from the exit code, not from the text output.
| Exit code | Meaning |
|---|---|
| 0 | Everything is formatted, or `--write` finished without errors |
| 1 | `--check` or `--list-different` found unformatted files |
| 2 | Prettier itself failed, for example with a syntax error, an invalid option, or no matching files |
You can see the code with echo $? in bash after a run. A common mistake is wiring prettier --write into CI. It exits 0 after reformatting, so the build passes while the committed code stays unformatted. Use --check in CI.
Common Errors and Gotchas
"No files matching the pattern were found"
This error happens when a glob matches nothing, or when every match is ignored. On macOS and Linux, quote globs so Prettier expands them consistently instead of your shell:
npx prettier "src/**/*.{js,mjs}" --checkWithout the quotes, bash without globstar reads ** as * and silently skips nested folders.
Syntax errors look like formatting failures
If one file has a parse error, Prettier prints the error with a line and column, exits with code 2, and leaves that file unchanged. It still processes the other files. Fix the syntax first. Prettier does not repair broken code.
Huge diffs on first run
The first --write on an existing codebase usually touches nearly every file. Commit that change on its own with a message like "Format with Prettier" so it does not bury real changes in review. You can then list the commit's hash in a .git-blame-ignore-revs file so git blame skips it.
Slow runs on large projects
Add --cache to skip files that have not changed since the last run:
npx prettier . --write --cacheThe cache lives in node_modules/.cache/prettier. It is keyed on file content, Prettier version, and options, so changing any of those invalidates it correctly.
Formatting text from stdin
Editors and other tools sometimes pipe code in instead of passing a path. Prettier then needs --stdin-filepath to choose a parser and find config:
echo "const x={a:1}" | npx prettier --stdin-filepath example.jsThe output is const x = { a: 1 };. The path does not need to exist. Prettier uses it only for its extension and for config lookup.
Exercises
Exercise
Your CI job runs npx prettier . --write and always passes, yet unformatted code keeps getting merged. Why, and what should the job run instead?
Show answer
--write reformats the files inside the CI workspace and exits 0, so the job never fails and the fixed files are thrown away when the job ends. Run npx prettier . --check, which exits 1 when any file is unformatted and fails the build.
Exercise
You run npx prettier src --write and get exit code 2, but some files were still reformatted. What most likely happened?
Show answer
At least one file had a syntax error. Prettier could not parse it, so it left that file unchanged and reported an error, which sets exit code 2. It still formatted the files it could parse.
Exercise
Why does Prettier recommend installing it with --save-exact?
Show answer
Prettier's output can change between versions, including patch releases. Pinning the exact version means every developer, editor, and CI run produces identical output, so files do not get reformatted back and forth between versions.
Exercise
Given const point = { followed by a newline, then x: 1, y: 2 };, what does Prettier output, and why does it differ from const point = {x: 1, y: 2};?
Show answer
It outputs the object expanded, with x: 1, and y: 2, on separate lines, each followed by a trailing comma. Prettier keeps an object expanded when the original source has a newline between { and the first key. Without that newline, the object fits within 80 columns and prints as const point = { x: 1, y: 2 };.