前端工程化实战:从代码规范、测试体系到 CI/CD 的全链路指南
本文深入探讨前端工程化的核心实践,涵盖 ESLint/Prettier 自动化规范、Husky 提交校验、测试奖杯模型以及 GitHub Actions 流水线配置,助你构建高可靠、可自动化的前端协作体系。
一、编码规范(自动化的第一道防线)
工具 | 职责 | 核心配置 |
|---|---|---|
ESLint | JS/TS 代码质量 + 潜在 bug 检查 | extends: ['eslint:recommended', 'plugin:@typescript-eslint/recommended'] |
Prettier | 代码格式化(不争论风格) | printWidth / singleQuote / trailingComma |
Stylelint | CSS/SCSS 规范检查 | extends: ['stylelint-config-standard'] |
TypeScript | 静态类型检查 | strict: true / noUncheckedIndexedAccess |
1. ESLint + Prettier 协作
用 eslint-config-prettier 关闭 ESLint 与 Prettier 冲突的格式规则
ESLint 9 Flat Config 示例
// eslint.config.js
import eslint from '@eslint/js';
import tseslint from 'typescript-eslint';
import react from 'eslint-plugin-react';
import prettier from 'eslint-config-prettier';
export default [
eslint.configs.recommended,
...tseslint.configs.recommended,
react.configs.flat.recommended,
prettier, // 放最后,关闭冲突规则
{
rules: {
'no-console': 'warn',
'@typescript-eslint/no-unused-vars': ['error', { argsIgnorePattern: '^_' }],
},
},
];二、Git 工作流与提交规范
1. Husky + lint-staged
pre-commit 钩子,只检查暂存区文件(增量检查,速度快)
2. Commitlint
规范 commit message 格式
完整配置示例
// package.json
{
"scripts": { "prepare": "husky" },
"lint-staged": {
"*.{ts,tsx}": ["eslint --fix", "prettier --write"],
"*.{css,scss}": ["stylelint --fix", "prettier --write"],
"*.{json,md}": ["prettier --write"]
}
}# .husky/pre-commit
npx lint-staged# .husky/commit-msg
npx commitlint --edit $1// commitlint.config.js
export default {
extends: ['@commitlint/config-conventional'],
// feat: 新功能 | fix: 修复 | docs: 文档 | style: 格式
// refactor: 重构 | perf: 性能 | test: 测试 | chore: 构建/工具
};3. 分支策略
Git Flow:feature / develop / release / hotfix(适合发版节奏固定)
Trunk-based:主干开发 + Feature Flag(适合持续部署)
三、测试体系
测试层级 | 工具 | 覆盖范围 | 成本 |
|---|---|---|---|
单元测试 | Vitest / Jest | 纯函数、工具类、hooks | 低 |
组件测试 | Testing Library | 组件渲染和交互 | 中 |
E2E 测试 | Playwright / Cypress | 完整用户流程 | 高 |
测试策略:测试金字塔 vs 奖杯模型
传统金字塔(Google) 测试奖杯(Kent C. Dodds)
△ E2E (少) ▽ E2E (少)
██ 集成 (中) ████ 集成 (最多) ← 投入产出比最高
████ 单元 (多) ██ 单元 (中)
█ 静态分析 (TypeScript/ESLint)现代前端推荐奖杯模型:集成测试(Testing Library 模拟用户操作)性价比最高
Vitest + Testing Library 示例
// utils.test.ts — 单元测试
import { describe, it, expect } from 'vitest';
import { formatPrice } from './utils';
describe('formatPrice', () => {
it('formats cents to dollar string', () => {
expect(formatPrice(1999)).toBe('$19.99');
});
it('handles zero', () => {
expect(formatPrice(0)).toBe('$0.00');
});
});
// LoginForm.test.tsx — 组件集成测试
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
it('submits login form with credentials', async () => {
const onSubmit = vi.fn();
render(<LoginForm onSubmit={onSubmit} />);
await userEvent.type(screen.getByLabelText('Email'), 'test@example.com');
await userEvent.type(screen.getByLabelText('Password'), '123456');
await userEvent.click(screen.getByRole('button', { name: 'Login' }));
expect(onSubmit).toHaveBeenCalledWith({ email: 'test@example.com', password: '123456' });
});四、CI/CD 流水线
GitHub Actions 完整质量门禁
name: CI
on: [push, pull_request]
jobs:
quality:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v2
- uses: actions/setup-node@v4
with: { node-version: 20, cache: pnpm }
- run: pnpm install --frozen-lockfile
- run: pnpm lint # ESLint + Stylelint
- run: pnpm type-check # tsc --noEmit
- run: pnpm test --coverage
- run: pnpm build
- uses: codecov/codecov-action@v3
with: { fail_ci_if_error: true }
deploy:
needs: quality
if: github.ref == 'refs/heads/main'
runs-on: ubuntu-latest
steps:
- run: pnpm build
- run: pnpm deploy:prod1. 质量门禁
Lint / 类型检查 / 测试 / 覆盖率 任一不过 → PR 不可合入
2. 部署策略
灰度发布:按比例放量(1% → 10% → 50% → 100%)
蓝绿部署:两套环境切换,回滚即秒级
Canary 部署:小流量验证新版本,监控无异常后全量
总结
核心心法
1. 工程化的本质是用自动化取代人为约束:Lint 管规范、Husky 管提交、CI 管合入
2. ESLint + Prettier + Stylelint 三件套是编码规范的标配,用eslint-config-prettier解决冲突
3. 测试策略推荐奖杯模型:集成测试性价比最高,单元测试兜底,E2E 保核心流程
4. CI/CD 流水线 = 质量门禁 + 自动部署,任一环节失败即阻断