如何配置ESLint检查提交信息格式

解读

面试官问的不是“如何用 ESLint 检查 .js/.ts 代码”,而是“如何用 ESLint 检查 Git 提交信息(commit message)本身”。
在国内一线厂与独角兽的面试里,这类问题常被用来区分“只会配 rules”与“能把代码质量工具嵌入研发流程”的候选人。
核心考点有三层:

  1. 是否意识到 ESLint 本身只能解析 JavaScript/TypeScript 源码,不能直接解析 commit message;
  2. 是否知道社区已提供“把 commit message 转成虚拟 JS 文件”的官方方案(eslint-plugin-commit-message);
  3. 能否把检查点无缝插入国内团队最常用的 Git Hooks + CI(如 GitLab-CI、Gitee-Go、阿里 Flow)流程,并给出可落地的配置片段。

知识点

  1. ESLint 插件机制:processor + rule,可把任意文本映射成虚拟文件供规则消费。
  2. eslint-plugin-commit-message:官方出品,内部用 processor 把 .git/COMMIT_EDITMSG 转成 JS 字符串,暴露规则如 commit-message/header-pattern、commit-message/empty-wip 等。
  3. 共享配置:extends 数组里可加入 plugin:commit-message/recommended,一键开启常用规则。
  4. Git Hooks 国内落地:
    • husky(v9 免安装)+ lint-staged 组合;
    • 或者 Node 工程自带 .git/hooks/commit-msg,直接调用 npx eslint --no-eslintrc --config .eslintrc.commit.js .git/COMMIT_EDITMSG。
  5. CI 卡点:在 GitLab-CI 的 commit-msg-check job 里复用同一套配置,保证合并请求阶段再次校验,防止本地绕过。
  6. 性能与缓存:commit message 检查耗时 <300 ms,可关闭 eslint --cache 避免额外 IO。

答案

步骤一:安装依赖
npm i -D eslint eslint-plugin-commit-message husky lint-staged

步骤二:在项目根新增专用配置 .eslintrc.commit.js
module.exports = {
root: true,
plugins: ['commit-message'],
extends: ['plugin:commit-message/recommended'],
rules: {
// 国内团队常用规范:type(scope): subject,type 只能小写,冒号后必须空一格
'commit-message/header-pattern': [
'error',
'^(feat|fix|docs|style|refactor|test|chore|perf)(\(.+\))?: .{1,50}'
],
'commit-message/empty-wip': 'error'
}
};

步骤三:注册 Git Hooks
package.json 追加:
"husky": {
"hooks": {
"commit-msg": "npx eslint --no-eslintrc --config .eslintrc.commit.js .git/COMMIT_EDITMSG"
}
}

步骤四:CI 二次校验(GitLab-CI 片段)
commit-msg-check:
stage: lint
script:
- npm ci
- npx eslint --no-eslintrc --config .eslintrc.commit.js .git/COMMIT_EDITMSG
only:
- merge_requests

验证:
git commit -m "wrong格式" # 被拦截
git commit -m "feat(core): 增加提交信息校验" # 通过

至此,提交信息格式被 ESLint 强制约束,且与 MR 流程打通,符合国内代码质量门禁要求。

拓展思考

  1. 多语言 monorepo 场景:若仓库含 Java/Go 子包,可把 commit-msg 检查拆成独立 job,使用同一套 Node 镜像,避免污染主构建。
  2. 自定义规则:基于 eslint-plugin-commit-message 的 processor,可编写私有规则,如“需求单号必须与 Jira 正则匹配”,直接放到 rules 目录并注册。
  3. 低权限团队(外包协作):提供封装好的 docker 镜像 kiwi/eslint-commit-checker,CI 阶段直接拉取,避免源码泄漏。
  4. 性能极限优化:对超大型仓库(10 万+ commit),CI 里可改为只校验当前 MR 的 commits 范围:
    BASE=(gitmerge−baseHEADorigin/master)gitlog−−format=(git merge-base HEAD origin/master) git log --format=%B {BASE}..HEAD | xargs -0 node scripts/lint-commit.js
    脚本内部仍调用 ESLint API,保证规则统一。