commit-msg钩子必须存在才能校验提交信息;未配置时commitlint不会运行,Husky默认不生成该钩子,需手动执行npx husky add .husky/commit-msg 'npx --no-install commitlint --edit $1'创建,并确保$1参数和--no-install选项正确。

commit-msg 钩子必须存在才能校验提交信息
没配 commit-msg 钩子,commitlint 就不会运行,哪怕装了包、写了配置也没用。Husky 默认只生成 pre-commit,你得手动加一个 commit-msg。
执行这行命令创建钩子:
npx husky add .husky/commit-msg 'npx --no-install commitlint --edit $1'
注意两点:
• $1 是 Git 传入的临时提交信息文件路径,不能漏
• --no-install 避免每次提交都试图重装依赖,尤其在 CI 或 pnpm 环境下容易失败
@commitlint/config-conventional 的 type 枚举不够用
默认规则只认 feat、fix 等几个 type,但 uni-app 项目常需要 uni(跨端适配)、mp(小程序平台相关)、h5(H5 平台定制)这类前缀,直接提交会报错:
subject must be lower-case 或 type must be one of [feat, fix, ...]
解决方法是在 commitlint.config.js 里显式扩展 type-enum 规则:
module.exports = {
extends: ['@commitlint/config-conventional'],
rules: {
'type-enum': [2, 'always', ['feat', 'fix', 'docs', 'style', 'refactor', 'test', 'uni', 'mp', 'h5']]
}
}
别忘了删掉 node_modules 重新 npm install,否则旧缓存可能让新规则不生效。
git cz 不能替代 commit-msg 校验
用 git cz 能生成合规 message,但它只是个输入辅助工具,不阻止手写违规 commit。比如有人绕过它直接 git commit -m "xxx",校验就失效了。
真正起作用的是 commit-msg 钩子——它在 Git 写完 message 后、真正落库前拦截并检查。
所以这两个要共存:
-
git cz降低团队成员使用门槛 -
commit-msg钩子兜底,强制所有提交都过校验
如果只配了 git cz 却没设钩子,CI 流水线或新成员第一次提交就可能被拒。
uni-app 项目里 husky 初始化容易卡在 git 仓库状态
Husky 要求项目已初始化为 git 仓库,且有 .git 目录。但 uni-app 常见情况是:用 vue create -p dcloudio/uni-preset-vue 创建后,还没 git init 就急着装 husky,结果 npx husky-init 报错或静默失败。
确认步骤:
- 进项目根目录,运行
git status,能看到On branch master才算 ok - 如果提示
not a git repository,先git init && git add . && git commit -m "init" - 再运行 husky 安装命令,否则
.husky文件夹根本建不起来
这个点在 uni-app 新建项目时特别容易被忽略,因为脚手架不自动初始化 git。











