前端代码质量保障有哪些手段?ESLint、Prettier、测试如何配置?
ESLint
// eslint.config.js(Flat Config,ESLint 9+)
import js from '@eslint/js'
import vue from 'eslint-plugin-vue'
import tsParser from '@typescript-eslint/parser'
export default [
js.configs.recommended,
...vue.configs['flat/recommended'],
{
files: ['**/*.{js,ts,vue}'],
languageOptions: {
parser: tsParser,
},
rules: {
'no-unused-vars': 'error',
'no-console': 'warn',
'prefer-const': 'error',
'vue/multi-word-component-names': 'off'
}
}
]常用规则:
no-unused-vars:未使用变量no-console:禁用 consoleeqeqeq:必须用 ===prefer-const:优先 constno-var:禁用 var
Prettier
// .prettierrc
{
"semi": false,
"singleQuote": true,
"tabWidth": 2,
"trailingComma": "none",
"printWidth": 100,
"arrowParens": "avoid"
}ESLint + Prettier 集成:
npm install -D eslint-config-prettier// 关闭与 Prettier 冲突的 ESLint 规则
export default [
...otherConfigs,
'prettier' // 放在最后
]Git Hooks(Husky + lint-staged)
npm install -D husky lint-staged
npx husky init// package.json
{
"lint-staged": {
"*.{js,ts,vue}": ["eslint --fix", "prettier --write"],
"*.{css,scss,json,md}": ["prettier --write"]
}
}# .husky/pre-commit
npx lint-stagedcommitlint(提交规范)
npm install -D @commitlint/cli @commitlint/config-conventional// commitlint.config.js
export default {
extends: ['@commitlint/config-conventional'],
rules: {
'type-enum': [2, 'always', [
'feat', 'fix', 'docs', 'style', 'refactor',
'perf', 'test', 'build', 'ci', 'chore', 'revert'
]]
}
}# .husky/commit-msg
npx --no-install commitlint --edit $1提交格式:feat: 添加用户登录功能
测试
单元测试(Vitest):
// sum.test.js
import { describe, it, expect } from 'vitest'
import { sum } from './sum'
describe('sum', () => {
it('should add two numbers', () => {
expect(sum(1, 2)).toBe(3)
})
it('should handle negative numbers', () => {
expect(sum(-1, -2)).toBe(-3)
})
})组件测试(Testing Library):
import { render, screen, fireEvent } from '@testing-library/vue'
import Counter from './Counter.vue'
test('increments on click', async () => {
render(Counter)
await fireEvent.click(screen.getByText('Count: 0'))
expect(screen.getByText('Count: 1')).toBeTruthy()
})E2E 测试(Playwright):
import { test, expect } from '@playwright/test'
test('login flow', async ({ page }) => {
await page.goto('/login')
await page.fill('[data-testid=email]', 'user@test.com')
await page.fill('[data-testid=password]', 'password')
await page.click('[data-testid=submit]')
await expect(page).toHaveURL('/dashboard')
})代码质量工具汇总
| 工具 | 作用 |
|---|---|
| ESLint | 代码规范检查 |
| Prettier | 代码格式化 |
| Husky | Git Hooks |
| lint-staged | 只检查暂存文件 |
| commitlint | 提交信息规范 |
| Vitest/Jest | 单元测试 |
| Testing Library | 组件测试 |
| Playwright/Cypress | E2E 测试 |
| TypeScript | 类型检查 |
| SonarQube | 代码质量扫描 |