Using Husky Pre-commit git hook with prettier

Automatically format on git commit

·

2 min read

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: gitlab.com/test-projects47/husky-prettier-l..

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: typicode.github.io/husky/#/?id=automatic-re..

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

  1. 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 with lint-staged and husky which creates too many terminal messages like below image.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