Skip to main content

Add a Git Commit Hook to Run Prettier on Only Staged Files in a NodeJS Project

Published: 2020-09-16 • Last updated: 2021-03-11

Prettier is a popular code formatter, and I especially like it for JS projects. You can add a script to run it with something like npm run prettier, but wouldn’t it be nice if it would run automatically every time you did a git commit? On top of that, say your project is huge with thousands of files, wouldn’t it be nice if prettier only ran on staged (changed) files?

Well, all of this is possible. See below for details. Make sure to update dependency versions as needed.

# Sample file tree


# .prettierrc.json

  "printWidth": 80,
  "tabWidth": 2,
  "useTabs": false,
  "semi": true,
  "singleQuote": true,
  "trailingComma": "none",
  "bracketSpacing": false,
  "arrowParens": "always",
  "proseWrap": "never",
  "endOfLine": "lf"

# package.json

  "scripts": {
    "prettier": "prettier --write src"
  "lint-staged": {
    "*.js": [
      "npm run prettier"
  "husky": {
    "hooks": {
      "pre-commit": "lint-staged"
  "dependencies": {
    "husky": "^4.2.5",
    "lint-staged": "^10.4.0",
    "prettier": "^2.1.2"