2017-11-07 14:39:07 +11:00
---
id : precommit
title : Pre-commit Hook
---
You can use Prettier with a pre-commit tool. This can re-format your files that are marked as "staged" via `git add` before you commit.
## Option 1. [lint-staged](https://github.com/okonet/lint-staged)
Install it along with [husky ](https://github.com/typicode/husky ):
```bash
yarn add lint-staged husky --dev
```
and add this config to your `package.json` :
```json
{
"scripts" : {
"precommit" : "lint-staged"
},
"lint-staged" : {
2017-12-06 10:34:58 +01:00
"*.{js,json,css,md}" : [ "prettier --write" , "git add" ]
2017-11-07 14:39:07 +11:00
}
}
```
2017-11-22 19:27:40 +08:00
2017-12-10 00:09:07 -02:00
**Warning:** Currently there is a limitation where if you stage specific lines this approach will stage the whole file after formatting. See this [issue ](https://github.com/okonet/lint-staged/issues/62 ) for more info.
2017-11-07 14:39:07 +11:00
See https://github.com/okonet/lint-staged#configuration for more details about how you can configure lint-staged.
2018-01-09 02:19:53 +11:00
## Option 2. [pretty-quick](https://github.com/azz/pretty-quick)
2017-12-21 04:08:42 +08:00
2018-01-09 02:19:53 +11:00
Install it along with [husky ](https://github.com/typicode/husky ):
2017-12-21 04:08:42 +08:00
```bash
2018-01-09 02:19:53 +11:00
yarn add pretty-quick husky --dev
2017-12-21 04:08:42 +08:00
```
and add this config to your `package.json` :
```json
{
"scripts" : {
2018-01-09 02:19:53 +11:00
"precommit" : "pretty-quick --staged"
}
2017-12-21 04:08:42 +08:00
}
```
2018-01-09 02:19:53 +11:00
Find more info from [here ](https://github.com/azz/pretty-quick ).
2017-12-21 04:08:42 +08:00
## Option 3. [pre-commit](https://github.com/pre-commit/pre-commit) (Python version)
2017-11-07 14:39:07 +11:00
Copy the following config into your `.pre-commit-config.yaml` file:
```yaml
- repo : https://github.com/prettier/prettier
sha : '' # Use the sha or tag you want to point at
hooks :
- id : prettier
```
Find more info from [here ](http://pre-commit.com ).
2017-12-21 04:08:42 +08:00
## Option 4. bash script
2017-11-07 14:39:07 +11:00
Alternately you can save this script as `.git/hooks/pre-commit` and give it execute permission:
```bash
#!/bin/sh
jsfiles = $( git diff --cached --name-only --diff-filter= ACM "*.js" "*.jsx" | tr '\n' ' ' )
[ -z " $jsfiles " ] && exit 0
# Prettify all staged .js files
echo " $jsfiles " | xargs ./node_modules/.bin/prettier --write
# Add back the modified/prettified files to staging
echo " $jsfiles " | xargs git add
exit 0
```