Prettier setup overview
Prettier is a great tool for formatting code. It enforces a consistent coding style across the entire code base. By utilizing the “format on save” feature in our IDE, we can automatically format the code based on the configuration provided in the .prettierrc
file. It will also give us good feedback when something is wrong with the code. If it doesn’t auto-format, something is wrong with the code and it needs to be fixed.
Prettier comes with a default configuration out of the box. We can override this by creating the .prettierrc
file and modifying the configuration.
Just as with ESLint, sometimes, there are files we do not want to auto-format. We can tell Prettier to ignore files and folders by adding them to the .
prettierignore
file.
To run Prettier, we have defined a couple of scripts in package.json
:
"prettier": "prettier \"**/*.+(json|ts|tsx)\"", "format:check": "npm run prettier -- --check", "format:fix": "npm run prettier -- --write",
As we can see, we can run npm run format:check
to just check the formatting without trying to fix it. If we want to fix it, then we can run npm run format:fix
, which will modify the files that need to be fixed.