11

I am using npm precommit hook, but it is not stopping a file with issues to be committed, nor am I getting the message "Pre commit checks" when I try to commit a file.

Package Json:
{
  "name": "myfolder",
  "version": "1.0.0",
  "description": "",
  "main": "",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 0",
    "precommit-msg": "echo 'Pre-commit checks...' && exit 0",
    "lint": "csslint global/css"
  },
  "author": "SR",
  "license": "ISC",
  "dependencies": {
    "csslint": "^1.0.4",
    "jshint": "^2.9.4",
    "pre-commit": "^1.2.2"
  },
  "pre-commit": [
    "precommit-msg",
    "lint"
  ],
  "devDependencies": {
    "pre-commit": "^1.2.2"
  }
}
user7258044
  • 121
  • 1
  • 1
  • 4

3 Answers3

11

Please, make sure that your 'package.json' file is in the same folder, where '.git' folder is (where git repository was initialized). When you install 'pre-commit' package, 'pre-commit' file should appear under '.git/hooks/'.

enter image description here

pasul
  • 1,182
  • 2
  • 12
  • 20
1

Just FYI I had this issue because the pre-commit file was missing in the hooks folder.

Running npm i pre-commit --save-dev again created the file and solved it for me.

Lukas Oppermann
  • 2,918
  • 6
  • 47
  • 62
0

Have't managed to implement it with few "pre-commit" NPM modules (@fastify/pre-commit, monorepo-staged-precommit) so implemented it "manually" with adding tools/pre-commit.sh file into repo with content like:

#!/bin/sh
DIR='web'
echo "Pre-commit actions (NPM tests for $DIR)..."
cd $DIR && npm run test

and updating package.json with:

"scripts": {
   "test",
   "install-precommit": "cp ../tools/pre-commit.sh ../.git/hooks/pre-commit"

This solution has some limitations (like instead of automatic installation need to ask somewhere in "README" about npm run install-precommit and I'm not sure how it would work on Windows especially without Git Bash) but it worked for me.

Notes:

  • Other pre-commit NPM packages either didn't work as well or asked for NVM and other extra tools which I don't want devs to install for such small task.
  • pre-commit.sh may has any name and don't be executable - "install-precommit" task and git care about.
AlexMakarov
  • 108
  • 1
  • 8