Search code examples
githusky

husky pre-commit hook not triggering


I am having an issue with husky. I would like for husky to run eslint and prettier at the point at which git commit is about to be done so that it can enforce clean coding checks. I have already setup eslint, prettier and integrated both. They are working fine when used manually. However, husky allows a commit if one of the eslint rules is violated.

I also renamed the pre-commit.sample file in my local project's .git/hooks directory to pre-commit.

This is my package.json file:

  "scripts": {
    "prettier-format": "prettier --config .prettierrc 'src/**/*.ts' 'test/**/*.ts' --write",
    "lint": "eslint . --ext .ts"
  },
  "husky": {
    "hooks": {
      "pre-commit": "npm run prettier-format && npm run lint"
    }
  },
  "devDependencies": {
    "husky": "^7.0.1"
  }

Please, what could be the problem here? Thank you very much.


Solution

  • I found an easier way to do this without having to initiate the installation of husky by myself.

    I installed lint-staged and tested husky pre-commit hooks that was setup by it by running the following commands:

    npx mrm@2 lint-staged
    yarn install
    
    

    The first line installs lint-staged and husky and adds the right sections with a sample script in the target package.json file for you to use or modify.

    Stage and commit the target package.json into git (local git is enough). Make a change that should cause the eslint find errors and the commit to fail. Try committing again to test the lint-staged setup. Lint-staged should prevent the files from being committed this time around.