使用GitHub Desktop提交时遇Husky错误:无法找到yarn.js模块
问题描述
在依赖Husky的项目中,使用GitHub Desktop提交变更或切换分支时出现以下错误:
2022-11-16T12:18:08.885Z - error: [ui] `git commit -F -` exited with an unexpected code: 1. stderr: /c/Users/user/AppData/Roaming/npm/yarn: line 5: cygpath: command not found node:internal/modules/cjs/loader:988 throw err; ^ Error: Cannot find module 'C:\Users\user\AppData\Local\GitHubDesktop\app-3.1.2\resources\app\git\node_modules\yarn\bin\yarn.js' at Module._resolveFilename (node:internal/modules/cjs/loader:985:15) at Module._load (node:internal/modules/cjs/loader:833:27) at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12) at node:internal/main/run_main_module:23:47 { code: 'MODULE_NOT_FOUND', requireStack: [] } Node.js v18.10.0 husky - pre-commit hook exited with code 1 (error)
环境信息:
- 操作系统:Windows 10 Pro
- GitHub Desktop:Version 3.1.2
- Git:Version 2.38.0.windows.1
- PowerShell中使用Git操作一切正常
解决方案
1. 切换GitHub Desktop使用系统全局Git
GitHub Desktop默认内置独立的Git/Node环境,和系统全局环境不兼容,切换到系统Git即可解决路径匹配问题:
- 打开GitHub Desktop,点击顶部菜单栏
File > Options - 切换到
Git选项卡,勾选Use the system Git - 点击
Browse选择系统Git的安装路径(通常是C:\Program Files\Git\bin\git.exe) - 重启GitHub Desktop后重试操作
2. 重新初始化Husky钩子
原有Husky钩子可能绑定了GitHub Desktop内置的Node环境,重新初始化可修复环境关联:
- 卸载当前Husky:
npm uninstall husky # yarn用户执行 yarn remove husky - 重新安装并初始化:
npx husky-init && npm install # yarn用户执行 npx husky-init --yarn2 && yarn install
3. 调整系统环境变量优先级
确保系统全局的Git、Node、Yarn路径在PATH最前端,让GitHub Desktop启动时优先读取全局环境:
- 右键「此电脑」>「属性」>「高级系统设置」>「环境变量」
- 在「系统变量」中找到
PATH,点击「编辑」 - 将以下路径移到顶部(根据实际安装路径调整):
C:\Program Files\Git\binC:\Users\你的用户名\AppData\Roaming\npmC:\Program Files\nodejs
- 保存后重启GitHub Desktop
4. 临时应急方案(不推荐长期使用)
如果需要立刻完成提交/分支切换,可以绕过Husky钩子:
git commit --no-verify # 切换分支时触发钩子的话,同样加参数 git checkout 目标分支 --no-verify
内容的提问来源于stack exchange,提问作者Metehan Altuntekin
相关产品推荐
相关产品推荐

