Prettier & Pre-commit hooks

Prettier & Pre-commit hooks

August 1, 2024
2024, Engineering
React, Nextjs, Notes

Introduction #

Prettier is a code formatter for JS projects. There are two variations we need to deal with when configuring prettier

Projects with package.json at root level #

For these projects we need to run following commands

npm install --save-dev --save-exact prettier
npx prettier . --write
npm install --save-dev husky lint-staged
npx husky init

This will install all the necessary packages. You need to create few config files using following commands

node --eval "fs.writeFileSync('.prettierrc','{}\n')"
node --eval "fs.writeFileSync('.prettierignore','# Ignore artifacts:\nbuild\ncoverage\n')"
node --eval "fs.writeFileSync('.husky/pre-commit','npx lint-staged\n')"

Finally you need to add following in package.json

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

Once all these steps are done there will be a .husky/pre-commit file. Enure contents should match like follows

npx lint-staged
npm run test

This will lint all files that are staged and run tests. Now every time you do a git commit it will lint all files and ensure all tests pass using Jest

Projects without package.json at root level #

You need to run above steps, plus few extra steps. For projects like Patentaware we don’t have frontend on root of the project. We need to follow few extra steps

  1. Goto cd .git/hooks in root directory of the project
  2. Crete commit hook mv commit-msg.sample commit-msg
  3. Ensure the contents of this file are as follows
#!/bin/sh
cd /Users/sidharthshah/Code/xc/patentaware/frontend/patentaware && ./.husky/pre-commit

Take a not you might have to change /Users/sidharthshah/Code/xc/patentaware/frontend/patentaware with correct path where you have installed your project