Prettier is an opinionated code formatter that automatically enforces consistent style rules for code, reducing formatting errors and improving readability.
Maintaining consistent code style across a project can be challenging, especially when working in a team. Enter Prettier, an opinionated code formatter that automatically formats your code to ensure consistency. Let’s explore how to add it to our node-based projects.
Installation
First, install Prettier locally:
Then, create an empty configuration file to let code editors and other tools know you are using Prettier:
Alternatively, if you want an example, here’s one I use:
Refer to Prettier’s documentation on the Configuration File.
Next, create a .prettierignore
file to let Prettier CLI and code editors know which files and directories to not format. For example:
This example would have Prettier ignore the build
, the public
directories, and the package-lock.json
file.
Now you can format all files with Prettier using:
Adding Scripts to Format the Entire Codebase
We can create scritps inside the package.json
file to make it easier for us to check and format the entire codebase with a simple npm/pnpm/yarn/bun command.
Inside your package.json
add the following scripts to check and format the codebase with Prettier.
And just like that, you can use: