Husky allows scripts to run at various git lifecycle events. Here, we want to use the Husky pre-commit hook to run prettier to automatically format the files in the repository on commit.
project setup on gitlab: https://gitlab.com/test-projects47/husky-prettier-lintstaged-test
Setup Husky
We set up husky automatically with husky-init
npx husky-init && npm install # npm
# or
npx husky-init && yarn # Yarn 1
A new folder, .husky is created in the root directory
Reference: https://typicode.github.io/husky/#/?id=automatic-recommended
Install Prettier
npm install prettier --save-dev
# or
yarn add prettier -D
Add prettier format script (optional)
add the following to package.json
, so we can use yarn format
to format all files with prettier
"scripts": {
...
"format": "prettier --write ."
}
Configure Husky
In .husky/pre-commit
, add yarn format
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"
yarn format
Now, yarn format
will run every time we use git commit
Only format staged files (optional)
With above setup, all files will be formatted. If we only want to format staged files, we can use lint-staged
- Install lint-staged ```
npm install lint-staged --save-dev
or
yarn add lint-staged -D
2. Add the lint-staged configuration to `package.json`
"scripts": {
...
},
"lint-staged": {
"*/.{js,jsx,ts,tsx}": [
"prettier --write"
]
},
"dependencies": {
...
},
...
3. Edit `.husky/pre-commit` file
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
npx lint-staged
Now, on git commit, prettier will only format, staged files, with specific file extension (js, jsx, ts, tsx) in this case.
but there's a [bug](https://github.com/typicode/husky/issues/968#issuecomment-1176848345) with lint-staged and husky which creates too many terminal messages like below
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/djeuvzfqb02ei7rq1334.png)
The temporary fix is as follow (in `.husky/pre-commit`),
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"
exec >/dev/tty 2>&1
npx lint-staged
Top comments (0)