Friday, September 13, 2019

pre-commit git hooks using husky

ESLint is already configured on my project.  There is a parent .eslintrc configuration file that is used for the backend code (uses Node.js).  There is also a child .eslintrc configuration file for the client code (uses React) that overrides/extends/adds rules that are different than for the backend.  I needed to run both npm scripts for linting during a git commit, using a pre-commit hook.

Other projects on my team uses manual written scripts that are installed in .git/hooks, but I decided to give husky a shot because:

  • don't have to remember to install it the custom bash script to .git/hooks or upgrade it
  • has over 1.5 million downloads and is actively maintained.  
  • can be bypassed with usual --no-verify.
    • git commit -m "TA-XXX:  Work and bypass git hooks" --no-verify
Environment:
CentOS Linux release 7.3.1611 (Core)
node v8.16.0
babel-eslint version "^10.0.2"
concurrently version "^3.1.0"
eslint version "^6.0.1"
eslint-plugin-flowtype version "^3.12.1"
eslint-plugin-import version "^2.18.2"
eslint-plugin-jsx-a11y version "^6.2.3"
eslint-plugin-react version "^7.14.2"
husky version "2.7.0"

Relevant npm scripts on the parent:
package.json

"clientlint": "cd client && npm run lint",
"lint": "node_modules/.bin/eslint -c .eslintrc .; exit 0",

Relevant npm script on the client child:
package.json

"lint": "node_modules/.bin/eslint -c .eslintrc .; exit 0"

Steps:
  1. Add husky as a dev dependency on the parent package.json file, and run npm/yarn package manager to install

  2. "devDependencies": {
      ...
      "husky": "2.7.0",
      ...
    }
    

  3. Configuring husky can be done in two different ways, both work great:
    • Using package.json:
      "husky": { 
        "hooks": { 
          "pre-commit": "npm run lint && npm run clientlint"
        }
      }
      
    • Using .huskyrc (DO NOT have "husky: {}" surrounding like it was in package.json file!)
      {
        "hooks": {
          "pre-commit": "npm run lint && npm run clientlint"
        }
      }
      

NOTE:  I submitted an issue Pre-commit fails with error when npm script calls "read with prompt" because I needed to add a npm script with a pause (I have now automated so this is OBE, but it is still a bug that has not been addressed by husky).

npm script in package.json:
"scripts": { 
  "clientlint": "cd client && npm run lint", 
  "clientcypress": "read -p Run Cypress and then press any key to continue",
  "lint": "node_modules/.bin/eslint -c .eslintrc .; exit 0"
}

.huskyrc file:
{
  "hooks": { 
    "pre-commit": "npm run clientcypress && npm run lint && npm run clientlint"
  }
}

1 comment:

I appreciate your time in leaving a comment!