Husky 4.x+ not working with Visual Studio Git

Nick picture Nick · Apr 13, 2020 · Viewed 8.9k times · Source

Husky changed it's path handling with 4.0.0. After this change, it throws the following error on commit from Visual Studio:

husky > pre-commit (node v12.12.0)/c/path/to/repo/node_modules/.bin/lint-staged: 
line 5: cygpath: command not foundinternal/modules/cjs/loader.js:797 throw err;

^Error: Cannot find module 'C:\lint-staged\bin\lint-staged.js' 
 at Function.Module._resolveFilename (internal/modules/cjs/loader.js:794:15) 
 at Function.Module._load (internal/modules/cjs/loader.js:687:27)
 at Function.Module.runMain (internal/modules/cjs/loader.js:1025:10) 
 at internal/main /run_main_module.js:17:11 { code: 'MODULE_NOT_FOUND', requireStack: []}

husky > pre-commit hook failed 
(add --no-verify to bypass)

However, when committing from CLI, it works as expected. Given that the error message has 'C:\lint-staged\bin\lint-staged.js' as the file path, I'm assuming that Visual Studio is handling the pathing differently.

I'm trying to find a way to make this work from within Visual Studio. I'm in an enterprise environment, so I'm hoping for a way I can include this configuration within the repo (rather than requiring manual local setup).

I have the husky config included within my package.json as

...
"husky":{
    "hooks":{ "pre-commit": "lint-staged"}
},
"lint-staged":{
    "!(*.min.*)js": "eslint --fix"
},
...

I'm currently using:
nvm 1.1.7 with Node 12.16.1
husky 4.2.5
lint-staged 10.1.3
visual studio 2019

Answer

Nick picture Nick · Apr 14, 2020

I found a solution, albeit it not a full explanation. The easy work around is to modify your husky command like so:

...
"husky":{
    "hooks":{ "pre-commit": "npx lint-staged"}
},
...

Specifying the NPM command corrects the issue with pathing. I found the suggestion in this response to an issue from 2018 in the lint-staged github, source here.

Edit: I just wanted to draw attention to TetraDev's comment. They are correct, you must include git add . in the lint staged tasks after the any code altering tasks (linting, prettier, etc) in order for the changes made to be applied to your commit.