How to automatically run Prettier on all files in a project

By

Learn how to run Prettier across every file in your project by adding a .prettierrc config and running npx prettier -w . to format them all at once.

~~~

To format every file in a project with Prettier, add a .prettierrc config file to the project root and run npx prettier -w . from there. Prettier walks the whole folder tree and rewrites each file it knows how to format.

This is what I do when I join an existing project that never used a formatter, or when I want to stop arguing with myself about tabs and semicolons. One command, and every file follows the same rules.

Add the configuration file

Create a .prettierrc file in your project, for example:

{
  "tabWidth": 2,
  "useTabs": false,
  "semi": false
}

This tells Prettier to indent with 2 spaces and drop semicolons. You can leave the file as an empty object {} if you’re happy with the defaults. Having the file in the repo matters anyway, because editors and other tools pick it up and apply the same rules.

Run Prettier on everything

Then run:

npx prettier -w .

The -w flag is short for --write. It edits the files in place instead of printing the result to the terminal. The . at the end means “start from the current folder”.

Prettier skips node_modules by default, so you don’t need to worry about it touching your dependencies.

If a folder should be left alone, like a dist or build folder, list it in a .prettierignore file. It works like .gitignore, one path per line.

Check without changing anything

You can also verify formatting without touching the files:

npx prettier --check .

This prints the files that are not formatted correctly. It’s what you’d run in CI to fail a build when someone commits unformatted code.

One pitfall

Running Prettier on an entire project changes a lot of files at once. If you mix that with real code changes, the diff becomes impossible to review.

The fix: commit all your pending work first, then run npx prettier -w . and put the result in its own dedicated commit. Anyone reading the history can skip that commit knowing nothing functional changed.

If you just need to tidy one snippet before committing, I built a free code beautifier that formats HTML, CSS, and JavaScript in the browser.

Tagged: Tools · All topics
~~~

Related posts about tools: