Setup Prettier in Your Project Quickly
Prettier is an "opinionated code formatter" that automatically formats your code according to predefined rules. It supports multiple languages and integrates seamlessly with most code editors. By using Prettier, you can:
- Ensure consistency across your entire codebase
- Save time and mental energy otherwise spent on manual formatting
- Reduce conflicts and discussions about code style in pull requests
- Focus on writing logic rather than arguing about semicolons or indentation
Here's a quick guide on setting up Prettier in your project so you and your team can enjoy these benefits.
Here's how to set it up:
1. Install Prettier:
npm install --save-dev prettier
2. Create a configuration file:
Create a .prettierrc
file in your project root and add your preferred options. For example:
{ "singleQuote": true, "trailingComma": "es5", "tabWidth": 2 }
3. Add scripts to your package.json
:
"scripts": { "format": "prettier --write \"**/*.{js,jsx,ts,tsx,json,css,scss,md}\"", "check-format": "prettier --check \"**/*.{js,jsx,ts,tsx,json,css,scss,md}\"" }
4. Run Prettier:
- To format all files:
npm run format
- To check formatting:
npm run check-format
5. (Optional) Set up your editor: If you use VS Code, install the Prettier extension for your code editor to format it on save.
That's it!