Have you ever opened a project where every file follows a different style? Some files use single quotes, others use double quotes. Some have semicolons, others don't. It's a mess, right? This is where Prettier comes in - it automatically formats your code so you and your team can focus on what matters: building great features.
Why Should You Care?
- Your code looks consistent across all files
- No more arguments about code style in team reviews
- Save time - let Prettier handle formatting while you write code
- Works perfectly with React and Next.js projects
Setting Up Prettier (It's Easy!)
Step 1: Install Prettier
npm install -D prettier
Step 2: Create Three Important Files
Tell Prettier what to format (.prettierrc):
{
"singleQuote": true,
"trailingComma": "es5",
"arrowParens": "always",
"tabWidth": 2,
"useTabs": false,
"printWidth": 100,
"bracketSpacing": true,
"jsxSingleQuote": false,
"jsxBracketSameLine": false,
"semi": true,
"importOrder": [
"^react$",
"^next",
"<THIRD_PARTY_MODULES>",
"^@/components/(.*)$",
"^@/utils/(.*)$",
"^[./]"
],
"importOrderSeparation": true,
"importOrderSortSpecifiers": true
}
Tell Prettier what to ignore (.prettierignore):
# Don't format these folders
node_modules
.next
build
dist
# Don't format these files
package-lock.json
yarn.lock
.env
.env.local
# Don't format images and icons
public/**/*.svg
public/**/*.png
public/**/*.jpg
Add commands to your package.json:
{
"scripts": {
"format": "prettier --write .",
"format:check": "prettier --check ."
}
}
How to Use It?
Format Your Code
# Format all files
npm run format
# Check if files need formatting
npm run format:check
Make It Work with VS Code
Add this to your VS Code settings:
{
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnSave": true
}
Now your code will format automatically when you save!
What Will This Fix?
Before Prettier:
const user={name:"John",
age:30,
email:"john@example.com"
}
After Prettier:
const user = {
name: 'John',
age: 30,
email: 'john@example.com',
};
Common Questions
- "Will this break my code?" No! Prettier only changes how your code looks, not how it works.
- "What if I don't like some formatting?" You can easily change any rule in the .prettierrc file.
- "Do I need to run format commands manually?" No - if you set up VS Code as shown above, it happens automatically when you save.
When You Need More
Want to make sure everyone on your team uses Prettier? Add this GitHub Action (.github/workflows/prettier.yml):
name: Check Code Formatting
on:
pull_request:
branches: [main]
jobs:
prettier:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
- run: npm ci
- run: npm run format:check
This will check if all code is properly formatted when someone makes a pull request.
Remember: Good code formatting is like good hygiene—it makes everyone's life easier and should be a daily habit!
Top comments (0)