.husky
pre-commit

Husky 🐶 + Lint-Staged + Prettier Setup

This guide will help you set up Husky, Lint-Staged, and Prettier in your project to enforce code formatting and linting on every commit.

Setting up Prettier and Husky

Install Prettier

npm install --save-dev --save-exact prettier

Create a Prettier configuration file

node --eval "fs.writeFileSync('.prettierrc','{}\n')"

Make .prettierignore file

# Ignore artifacts:
build
coverage
# .next
⚠️

Make sure to add the files and directories you want to ignore in the .prettierignore file. If you are using Next.js you can add .next to the .prettierignore file.

Install Husky and Lint-Staged

npm install --save-dev husky lint-staged
npx husky init
node --eval "fs.writeFileSync('.husky/pre-commit','npx lint-staged\n')"

package.json file

  "lint-staged": {
    "**/*": "prettier --write --ignore-unknown"
  }

.husky/pre-commit file

#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"
 
npm exec lint-staged # or yarn exec lint-staged or pnpm exec lint-staged 👍🏻
 

Conclusion

You have successfully set up Husky, Lint-Staged, and Prettier in your project. Now, every time you commit, Husky will run Lint-Staged, which will run Prettier on your staged files.