DEV Community

Cheryl M for Web Dev Path

Posted on

Using Husky Pre-commit git hook with prettier

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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 ."
  }
Enter fullscreen mode Exit fullscreen mode

Configure Husky

In .husky/pre-commit, add yarn format

#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"

yarn format

Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode
  1. Add the lint-staged configuration to package.json
"scripts": {
    ...
  },
  "lint-staged": {
    "**/*.{js,jsx,ts,tsx}": [
      "prettier --write"
    ]
  },
  "dependencies": {
    ...
  },
  ...
Enter fullscreen mode Exit fullscreen mode
  1. Edit .husky/pre-commit file
    #!/bin/sh
    . "$(dirname "$0")/_/husky.sh"

    npx lint-staged
Enter fullscreen mode Exit fullscreen mode

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 description

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
Enter fullscreen mode Exit fullscreen mode

Latest comments (0)