Course contentsShow
← JavaScript
Lesson 2577 of 2,72352. Linting and FormattingFree lesson

Installing and Running Prettier

Set up Prettier locally, format files via CLI, and understand the --write flag.

Installing and Running Prettier

You'll learn how to add Prettier to your project, format code from the command line, and understand the crucial --write flag.

What Prettier Does for You

Prettier is a code formatter that enforces consistent style across your project. Unlike ESLint (which you've already learned), Prettier doesn't care about code quality—it only cares about how your code looks. Think of it like autocorrect for formatting: you write code your way, then Prettier rewrites it according to consistent rules.

Installing Prettier Locally

Just like ESLint, you'll want Prettier as a dev dependency:

npm install --save-dev prettier

This adds Prettier to your package.json under devDependencies and downloads it into node_modules.

Running Prettier from the CLI

To check how Prettier would format a file without changing it:

npx prettier index.js

This prints the formatted version to your terminal but leaves the original file untouched. It's like a preview.

To actually rewrite your files with proper formatting:

npx prettier --write index.js

The --write flag tells Prettier to modify the file in place. You can format multiple files or entire directories:

npx prettier --write "src/**/*.js"

This glob pattern formats all JavaScript files in your src folder and subdirectories.

The Power of --write

The --write flag is what makes Prettier practical. Without it, you'd manually copy-paste formatted output. With it, Prettier becomes a one-command code cleanup tool. You'll typically add this to your package.json scripts for convenience:

"scripts": {
  "format": "prettier --write ."
}

Then run npm run format to format your entire project.

Key Takeaway: Install Prettier locally with npm install --save-dev prettier, preview formatting with npx prettier <file>, and apply changes permanently with the --write flag.