You can use Prettier to make your code more readable and consistent with your style guide. There are several ways to start Prettier automatically, these are the most popular when using Git:
1. pretty-quick
Use library pretty-quick to format your changed or staged files.
npx husky-init
npm install --save-dev pretty-quick
npx husky set .husky/pre-commit "npx pretty-quick --staged"
2. Shell script
Save this script as .git/hooks/pre-commit
and give it execute permission:
#!/bin/sh
FILES=$(git diff --cached --name-only --diff-filter=ACMR | sed 's| |\\ |g')
[ -z "$FILES" ] && exit 0
# Prettify all selected files
echo "$FILES" | xargs ./node_modules/.bin/prettier --ignore-unknown --write
# Add back the modified/prettified files to staging
echo "$FILES" | xargs git add
exit 0
If git is reporting that your prettified files are still modified after committing, you may need to add a post-commit script to update git’s index.
Add something like the following to .git/hooks/post-commit
:
#!/bin/sh
git update-index -g
Configure rules
Create a *.prettierrc
file at the root of your project to configure your prettier rules.
Here's an example file containing some popular rules:
{
"semi": true",
"trailingComma": "all",
"singleQuote": true,
"printWidth": 70,
"arrowParens": "always",
"tabWidth": 2
}
For everything you don't want to format, create a .prettierignore file:
node_modules/
package.json
Manual Run & Fix
To manual run via CLI, add a command to package.json and run npm run format
.
{
"scripts": {
"format": "prettier --write ."
}
}
Top comments (0)