上周五下午 5 点,同事提了个 PR,被 CI 卡了 7 次:
- 缩进不对
- 多了个 console.log
- 提交信息写的是 "fix bug"
- ESLint 报了 3 个 warning
他崩溃地问:"就不能在我本地就告诉我错了吗?"
我说:"能------但你们没配。"
今天,我就手把手教你搭建一套 Vue 3 项目开箱即用的自动化工程化流水线,包含:
- 代码格式自动修复
- 提交信息规范校验
- Git Hooks 拦截脏提交
- CI 零配置集成
全程只需 15 分钟,从此告别"格式战争"。
核心工具链(2026 年推荐组合)
| 功能 | 工具 | 优势 |
|---|---|---|
| 代码格式化 | Prettier | 统一风格,无配置争议 |
| 代码检查 | ESLint + TypeScript | 逻辑错误 + 类型安全 |
| 提交规范 | Commitlint + Husky | 强制 Angular 风格 commit |
| 本地拦截 | lint-staged | 只检查 staged 文件,快! |
| 构建集成 | Vite + GitHub Actions | CI 自动跑检查 |
关键理念:本地自动修,提交前拦截,CI 只做最终守门员
第一步:统一代码风格 ------ Prettier + ESLint 联合治理
1. 安装依赖
bash
npm install -D prettier eslint @typescript-eslint/eslint-plugin eslint-config-prettier
2. 配置 .prettierrc
json
{
"semi": true,
"singleQuote": true,
"tabWidth": 2,
"trailingComma": "es5",
"printWidth": 100
}
3. 配置 .eslintrc.js(关键:让 ESLint 不管格式)
js
module.exports = {
extends: [
'eslint:recommended',
'@typescript-eslint/recommended',
'prettier' // ← 关闭 ESLint 与 Prettier 冲突的规则
],
plugins: ['@typescript-eslint'],
parserOptions: { ecmaVersion: 2020, sourceType: 'module' }
};
效果:
- ESLint 只管逻辑错误(如未使用变量)
- Prettier 只管格式(如引号、缩进)
- 两者不再打架!
第二步:提交前自动修复 ------ lint-staged + Husky
1. 初始化 Git Hooks
bash
npx husky-init && npm install
2. 配置 package.json 中的 lint-staged
json
{
"lint-staged": {
"*.{js,ts,vue}": [
"eslint --fix",
"prettier --write"
]
}
}
3. 修改 .husky/pre-commit
bash
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"
npx lint-staged
效果:
当你运行
git commit,只有你改动的文件会被自动格式化 + 修复 ,如果有无法修复的错误(如类型错误),提交直接失败!
第三步:规范提交信息 ------ Commitlint
1. 安装
bash
npm install -D @commitlint/cli @commitlint/config-conventional
2. 创建 commitlint.config.js
js
module.exports = {
extends: ['@commitlint/config-conventional']
};
3. 添加 commit-msg Hook
bash
npx husky add .husky/commit-msg 'npx --no-install commitlint --edit $1'
现在,提交信息必须符合格式:
scssfeat(auth): add login button fix(api): handle timeout error docs(readme): update installation guide否则:
git commit -m "update"→ 直接拒绝!
第四步:CI 自动守门(GitHub Actions 示例)
在 .github/workflows/ci.yml 中添加:
yaml
name: CI
on: [push]
jobs:
lint:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with: { node-version: 18 }
- run: npm ci
- run: npm run lint # 检查 ESLint
- run: npm run format:check # 检查 Prettier
并在 package.json 中定义脚本:
json
{
"scripts": {
"lint": "eslint . --ext .js,.ts,.vue",
"format:check": "prettier --check ."
}
}
效果:即使有人绕过本地 Hooks(比如
--no-verify),CI 也会拦住他!
最终效果:开发者体验流程图
sql
你写代码
↓
保存时 → VS Code 自动格式化(通过 EditorConfig + Prettier 插件)
↓
git add .
↓
git commit → Husky 触发
├─ lint-staged: 自动修复 staged 文件
└─ commitlint: 校验提交信息格式
↓
推送 → GitHub Actions 运行完整检查
↓
合并!零格式争议,零低级错误
最后说两句
工程化不是"加流程",而是减少人为摩擦。
一套好的工具链,应该像空气------
你感觉不到它存在,但一旦没了,立刻窒息。
花 15 分钟配好它,
未来省下的是几百小时的 Code Review 和 debug 时间。
有没有因为格式问题吵过架?欢迎留言区分享
各位互联网搭子,要是这篇文章成功引起了你的注意,别犹豫,关注、点赞、评论、分享走一波,让我们把这份默契延续下去,一起在知识的海洋里乘风破浪!