Cursor作为AI编程助手,可以通过自定义规则模板来大幅降低前端开发bug率。本文提供了一套增强版的前端开发规则模板,集成了自测规范、代码审查清单、组件化开发、性能优化等全方位质量保障体系,确保生成零缺陷的现代化前端代码。
🎨 Cursor规则模板的核心设计理念
1. 零缺陷前端编程哲学
🖼️ 核心原则(增强版)
1 2 3 4 5 6 7 8 9 10
| 你现在是一名追求零缺陷的现代化前端架构师,具备以下核心编程理念:
1. **用户体验至上**:每个交互都经过可用性测试验证 2. **性能为王**:零性能劣化,追求极致用户体验 3. **无障碍友好**:WCAG 2.1 AA级无障碍访问标准 4. **跨平台兼容**:完美支持桌面、移动、平板设备 5. **自测先行**:组件测试先行,E2E测试保障 6. **类型安全**:TypeScript严格模式,杜绝运行时错误 7. **可访问性优先**:键盘导航、屏幕阅读器完美支持 8. **渐进增强**:核心功能不依赖JavaScript运行
|
🚀 增强前端技术栈(零缺陷版)
1 2 3 4 5 6 7 8 9 10 11 12
| 现代化前端零缺陷技术栈: - **框架**:React 18 + Next.js 14 + TypeScript 5.x - **构建工具**:Vite 5.x + Turbopack + SWC - **样式方案**:Tailwind CSS + CSS Modules + Styled Components - **状态管理**:Zustand + React Query + Context API - **路由**:Next.js App Router + React Router v6 - **测试**:Jest + React Testing Library + Playwright + Vitest - **代码质量**:ESLint + Prettier + Husky + Commitlint - **组件开发**:Storybook + Chromatic + Figma - **性能监控**:Lighthouse CI + Web Vitals + Sentry - **部署**:Vercel + Netlify + AWS Amplify - **文档**:Storybook + MDX + TypeDoc
|
🏗️ 增强版前端架构设计规则模板
1. 零缺陷前端项目结构规范
📁 现代化前端项目结构(Next.js + TypeScript)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
|
|
🧪 前端自测驱动的项目结构
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
|
#### 📱 响应式设计与设备适配 ```typescript /** * 响应式断点系统(移动优先) */ export const breakpoints = { sm: '640px', // 小屏幕手机 md: '768px', // 大屏幕手机/小平板 lg: '1024px', // 平板/小笔记本 xl: '1280px', // 桌面显示器 '2xl': '1536px' // 大屏幕显示器 } as const
/** * 设备类型检测Hook */ export function useDeviceType() { const [deviceType, setDeviceType] = useState<DeviceType>('desktop')
useEffect(() => { const checkDeviceType = () => { const width = window.innerWidth if (width < 640) setDeviceType('mobile') else if (width < 1024) setDeviceType('tablet') else setDeviceType('desktop') }
checkDeviceType() window.addEventListener('resize', checkDeviceType) return () => window.removeEventListener('resize', checkDeviceType) }, [])
return deviceType }
/** * 触摸设备检测 */ export const isTouchDevice = () => { return 'ontouchstart' in window || navigator.maxTouchPoints > 0 }
|
🧪 增强版前端自测规范(组件测试 + E2E测试)
1. 测试驱动的前端开发规范
🎯 前端测试金字塔
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| 前端测试层次(从下到上): 1. **单元测试** (Unit Tests) - 60%覆盖率 - 单个函数/组件的逻辑测试 - 快速执行,无外部依赖 2. **集成测试** (Integration Tests) - 25%覆盖率 - 组件间协作和数据流测试 - API调用和状态管理测试 3. **端到端测试** (E2E Tests) - 15%覆盖率 - 完整用户流程测试 - 跨页面交互测试
测试策略: - **Given-When-Then**:行为驱动测试模式 - **AAA模式**:Arrange-Act-Assert测试结构 - **测试数据管理**:使用工厂模式生成测试数据
|
🧩 组件单元测试规范(React Testing Library)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
| import { render, screen, fireEvent, waitFor } from '@testing-library/react' import userEvent from '@testing-library/user-event' import { LoginForm } from './LoginForm'
describe('LoginForm', () => { const mockOnSubmit = jest.fn() const user = userEvent.setup()
beforeEach(() => { mockOnSubmit.mockClear() })
describe('✅ 正常登录流程', () => { it('应该成功提交有效的登录表单', async () => { render(<LoginForm onSubmit={mockOnSubmit} />)
const emailInput = screen.getByRole('textbox', { name: /邮箱/i }) const passwordInput = screen.getByLabelText(/密码/i) const submitButton = screen.getByRole('button', { name: /登录/i })
await user.type(emailInput, 'user@example.com') await user.type(passwordInput, 'password123') await user.click(submitButton)
await waitFor(() => { expect(mockOnSubmit).toHaveBeenCalledWith({ email: 'user@example.com', password: 'password123' }) })
expect(emailInput).toHaveAttribute('aria-describedby') expect(passwordInput).toHaveAttribute('type', 'password') }) })
describe('❌ 表单验证错误处理', () => { it('应该显示邮箱格式错误', async () => { render(<LoginForm onSubmit={mockOnSubmit} />)
const emailInput = screen.getByRole('textbox', { name: /邮箱/i }) const submitButton = screen.getByRole('button', { name: /登录/i })
await user.type(emailInput, 'invalid-email') await user.click(submitButton)
expect(screen.getByText(/邮箱格式不正确/i)).toBeInTheDocument() expect(emailInput).toHaveAttribute('aria-invalid', 'true') expect(submitButton).toBeDisabled() })
it('应该显示密码长度不足错误', async () => { render(<LoginForm onSubmit={mockOnSubmit} />)
const passwordInput = screen.getByLabelText(/密码/i) const submitButton = screen.getByRole('button', { name: /登录/i })
await user.type(passwordInput, '123') await user.click(submitButton)
expect(screen.getByText(/密码长度至少6位/i)).toBeInTheDocument() }) })
describe('♿ 无障碍访问测试', () => { it('应该支持键盘导航', async () => { render(<LoginForm onSubmit={mockOnSubmit} />)
const emailInput = screen.getByRole('textbox', { name: /邮箱/i }) const passwordInput = screen.getByLabelText(/密码/i) const submitButton = screen.getByRole('button', { name: /登录/i })
emailInput.focus() expect(document.activeElement).toBe(emailInput)
fireEvent.keyDown(emailInput, { key: 'Tab' }) expect(document.activeElement).toBe(passwordInput)
fireEvent.keyDown(passwordInput, { key: 'Tab' }) expect(document.activeElement).toBe(submitButton) })
it('应该支持屏幕阅读器', () => { render(<LoginForm onSubmit={mockOnSubmit} />)
const emailInput = screen.getByRole('textbox', { name: /邮箱/i }) const passwordInput = screen.getByLabelText(/密码/i })
expect(emailInput).toHaveAttribute('aria-required', 'true') expect(passwordInput).toHaveAttribute('aria-required', 'true') expect(passwordInput).toHaveAttribute('aria-describedby') }) }) })
|
🌐 端到端测试规范(Playwright)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
| import { test, expect } from '@playwright/test'
test.describe('用户登录流程', () => { test.beforeEach(async ({ page }) => { await page.context().addCookies([{ name: 'test-mode', value: 'true', domain: 'localhost', path: '/' }]) })
test('✅ 完整用户登录到仪表板流程', async ({ page }) => { await page.goto('/login')
await expect(page).toHaveTitle(/登录/) await expect(page.locator('h1')).toContainText('用户登录')
await page.getByRole('textbox', { name: /邮箱/ }).fill('user@example.com') await page.getByLabel('密码').fill('password123')
await page.getByRole('button', { name: /登录/ }).click()
await expect(page).toHaveURL('/dashboard') await expect(page.locator('[data-testid="welcome-message"]')) .toContainText('欢迎回来')
await page.getByRole('button', { name: /用户菜单/ }).click() await page.getByRole('menuitem', { name: /个人资料/ }).click() await expect(page).toHaveURL('/profile')
await page.reload() await expect(page.locator('[data-testid="user-email"]')) .toContainText('user@example.com') })
test('❌ 登录失败错误处理', async ({ page }) => { await page.goto('/login')
await page.getByRole('textbox', { name: /邮箱/ }).fill('wrong@example.com') await page.getByLabel('密码').fill('wrongpassword') await page.getByRole('button', { name: /登录/ }).click()
await expect(page.getByText(/邮箱或密码错误/)).toBeVisible()
await expect(page).toHaveURL('/login')
await expect(page.getByLabel('密码')).toHaveValue('') })
test('📱 移动端登录体验', async ({ page }) => { await page.setViewportSize({ width: 375, height: 667 })
await page.goto('/login')
await expect(page.locator('.mobile-form')).toBeVisible() await expect(page.locator('.desktop-form')).toBeHidden()
await page.getByRole('textbox', { name: /邮箱/ }).tap() await page.keyboard.type('mobile@example.com')
await page.getByLabel('密码').tap() await page.keyboard.type('password123')
await page.getByRole('button', { name: /登录/ }).tap()
await expect(page).toHaveURL('/dashboard') }) })
|
🔍 前端代码审查规范(现代化前端标准)
1. 自动化代码审查清单
🛡️ 前端静态代码分析规则
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| ESLint + Prettier + TypeScript ESLint自动检查项:
1. **代码质量检查** - [ ] TypeScript严格模式启用 - [ ] 显式类型注解(非any类型) - [ ] 函数复杂度 <= 10 - [ ] 组件文件大小 <= 300行 - [ ] 重复代码率 <= 5%
2. **React最佳实践检查** - [ ] 使用函数组件 + Hooks - [ ] 依赖数组完整声明 - [ ] 避免不必要的重新渲染 - [ ] 正确使用useEffect清理 - [ ] 组件命名使用PascalCase
3. **无障碍访问检查** - [ ] 语义化HTML标签 - [ ] ARIA属性正确使用 - [ ] 键盘导航支持 - [ ] 颜色对比度 >= 4.5:1 - [ ] 屏幕阅读器兼容
4. **性能优化检查** - [ ] 避免大对象inline - [ ] 图片懒加载实现 - [ ] Bundle大小控制 - [ ] 首屏加载优化 - [ ] 内存泄漏防范
|
📋 前端人工代码审查清单
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| ### 第一轮:功能完整性 - [ ] **用户交互**:所有交互场景正确实现 - [ ] **数据流转**:状态管理和数据传递正确 - [ ] **错误处理**:网络错误、用户错误妥善处理 - [ ] **边界情况**:加载状态、空数据、异常状态处理 - [ ] **跨浏览器**:主流浏览器兼容性验证
### 第二轮:用户体验质量 - [ ] **响应式设计**:移动端、平板、桌面端适配 - [ ] **无障碍访问**:键盘导航、屏幕阅读器支持 - [ ] **性能表现**:加载速度、交互流畅性 - [ ] **视觉一致性**:设计系统遵循、视觉层次清晰 - [ ] **国际化支持**:多语言、本地化处理
### 第三轮:代码质量与架构 - [ ] **类型安全**:TypeScript类型定义完整 - [ ] **组件设计**:职责单一、可复用性强 - [ ] **状态管理**:状态结构合理、更新逻辑清晰 - [ ] **测试覆盖**:单元测试、集成测试完善 - [ ] **代码组织**:文件结构清晰、命名规范
|
2. 前端组件抽取策略(设计系统驱动)
🎨 组件设计系统
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
| interface ButtonProps { variant: 'primary' | 'secondary' | 'outline' | 'ghost' size: 'sm' | 'md' | 'lg' disabled?: boolean loading?: boolean children: React.ReactNode onClick?: () => void }
interface InputProps { type?: 'text' | 'email' | 'password' | 'number' placeholder?: string value?: string onChange?: (value: string) => void error?: string required?: boolean disabled?: boolean }
const buttonVariants = cva( 'inline-flex items-center justify-center rounded-md font-medium transition-colors', { variants: { variant: { primary: 'bg-blue-600 text-white hover:bg-blue-700', secondary: 'bg-gray-600 text-white hover:bg-gray-700', outline: 'border border-gray-300 bg-white hover:bg-gray-50', ghost: 'text-gray-700 hover:bg-gray-100', }, size: { sm: 'h-8 px-3 text-sm', md: 'h-10 px-4 text-base', lg: 'h-12 px-6 text-lg', }, disabled: { true: 'opacity-50 cursor-not-allowed', }, }, defaultVariants: { variant: 'primary', size: 'md', disabled: false, }, } )
|
🔧 前端重构模式库
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
|
## ⚡ 前端性能优化规范(零性能劣化)
### 1. 前端性能监控体系
#### 📊 Web Vitals性能指标监控 ```typescript // ✅ 核心Web Vitals监控 import { getCLS, getFID, getFCP, getLCP, getTTFB } from 'web-vitals'
export function reportWebVitals(onPerfEntry?: (metric: any) => void) { if (onPerfEntry && onPerfEntry instanceof Function) { getCLS(onPerfEntry) getFID(onPerfEntry) getFCP(onPerfEntry) getLCP(onPerfEntry) getTTFB(onPerfEntry) } }
// 🎯 性能指标收集和上报 class PerformanceMonitor { private metrics: Map<string, number> = new Map()
startTracking(name: string) { this.metrics.set(`${name}_start`, performance.now()) }
endTracking(name: string) { const startTime = this.metrics.get(`${name}_start`) if (startTime) { const duration = performance.now() - startTime this.metrics.set(`${name}_duration`, duration)
// 上报性能指标 this.reportMetric(name, duration)
// 性能告警检查 if (duration > this.getThreshold(name)) { this.alertSlowPerformance(name, duration) } } }
private getThreshold(name: string): number { const thresholds: Record<string, number> = { 'api_call': 500, // API调用不超过500ms 'component_render': 16, // 组件渲染不超过16ms (60fps) 'image_load': 2000, // 图片加载不超过2s 'page_load': 3000, // 页面加载不超过3s } return thresholds[name] || 1000 }
private reportMetric(name: string, duration: number) { // 发送到监控系统 (Sentry, DataDog, etc.) console.log(`Performance: ${name} took ${duration.toFixed(2)}ms`)
// 可以集成第三方监控服务 if (typeof window !== 'undefined' && window.gtag) { window.gtag('event', 'performance_metric', { event_category: 'performance', event_label: name, value: Math.round(duration) }) } }
private alertSlowPerformance(name: string, duration: number) { // 性能告警逻辑 console.warn(`⚠️ 性能警告: ${name} 执行时间过长 (${duration.toFixed(2)}ms)`)
// 可以发送告警通知 // this.sendAlert({ type: 'performance', name, duration }) } }
// 🚀 全局性能监控实例 export const performanceMonitor = new PerformanceMonitor()
|
🎯 前端性能优化清单
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| ### 加载性能优化 - [x] **代码分割**:路由级懒加载,组件动态导入 - [x] **资源优化**:图片压缩,字体子集化,CSS/JS压缩 - [x] **缓存策略**:HTTP缓存,Service Worker缓存策略 - [x] **CDN加速**:静态资源CDN分发,边缘计算 - [x] **预加载**:关键资源预加载,DNS预解析
### 运行时性能优化 - [x] **渲染优化**:虚拟滚动,列表虚拟化,图片懒加载 - [x] **内存管理**:组件卸载清理,事件监听器移除 - [x] **计算优化**:useMemo缓存计算,useCallback稳定引用 - [x] **Bundle优化**:Tree Shaking,代码分割,按需加载
### 用户体验优化 - [x] **交互反馈**:Loading状态,Skeleton屏,过渡动画 - [x] **错误处理**:优雅降级,错误边界,离线支持 - [x] **响应式设计**:移动优先,断点系统,触摸优化 - [x] **无障碍访问**:键盘导航,屏幕阅读器,焦点管理
|
2. 前端性能优化模式
🚀 React性能优化最佳实践
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
| import React, { memo, useMemo, useCallback } from 'react'
const ExpensiveComponent = memo(({ data, onAction }: ExpensiveProps) => { return ( <div> {data.map(item => ( <ItemComponent key={item.id} item={item} onAction={onAction} /> ))} </div> ) })
const DataProcessor = ({ rawData, filter }: DataProcessorProps) => { const processedData = useMemo(() => { return rawData.filter(item => item.status === filter) }, [rawData, filter])
return <DataList data={processedData} /> }
const ActionButton = ({ onClick, label }: ActionButtonProps) => { const handleClick = useCallback(() => { onClick(label) }, [onClick, label])
return <button onClick={handleClick}>{label}</button> }
import { FixedSizeList as List } from 'react-window'
const VirtualizedList = ({ items }: VirtualizedListProps) => { return ( <List height={400} itemCount={items.length} itemSize={50} width="100%" > {({ index, style }) => ( <div style={style}> <ListItem item={items[index]} /> </div> )} </List> ) }
const LazyImage = ({ src, alt, ...props }: LazyImageProps) => { const [imageSrc, setImageSrc] = useState(placeholder) const [imageRef, setImageRef] = useState<HTMLImageElement | null>(null)
useEffect(() => { const observer = new IntersectionObserver( (entries) => { if (entries[0].isIntersecting) { setImageSrc(src) observer.disconnect() } }, { threshold: 0.1 } )
if (imageRef) observer.observe(imageRef)
return () => observer.disconnect() }, [src, imageRef])
return ( <img ref={setImageRef} src={imageSrc} alt={alt} loading="lazy" {...props} /> ) }
|
🔒 前端安全开发规范
1. 前端安全威胁防护
🛡️ XSS防护策略
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
| import DOMPurify from 'dompurify'
const sanitizeHtml = (dirty: string): string => { return DOMPurify.sanitize(dirty, { ALLOWED_TAGS: ['p', 'br', 'strong', 'em', 'u'], ALLOWED_ATTR: ['href', 'target'], ALLOW_DATA_ATTR: false }) }
const SafeHtmlComponent = ({ htmlContent }: SafeHtmlProps) => { const sanitizedContent = useMemo(() => { return { __html: sanitizeHtml(htmlContent) } }, [htmlContent])
return <div dangerouslySetInnerHTML={sanitizedContent} /> }
const getSafeUrlParam = (paramName: string): string | null => { const url = new URL(window.location.href) const param = url.searchParams.get(paramName)
if (!param) return null
const safePattern = /^[a-zA-Z0-9\-_.]+$/ return safePattern.test(param) ? param : null }
const loadScriptSafely = (src: string): Promise<void> => { return new Promise((resolve, reject) => { const url = new URL(src, window.location.origin) if (url.protocol !== 'https:') { reject(new Error('只允许HTTPS脚本')) return }
const script = document.createElement('script') script.src = src script.integrity = 'sha256-...' script.crossOrigin = 'anonymous'
script.onload = () => resolve() script.onerror = () => reject(new Error('脚本加载失败'))
document.head.appendChild(script) }) }
|
🔐 CSRF防护策略
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
| class ApiClient { private csrfToken: string = ''
constructor() { this.initializeCsrfToken() }
private async initializeCsrfToken() { try { const response = await fetch('/api/csrf-token', { method: 'GET', credentials: 'same-origin' }) const data = await response.json() this.csrfToken = data.token } catch (error) { console.error('获取CSRF令牌失败:', error) } }
async post(url: string, data: any) { const headers: Record<string, string> = { 'Content-Type': 'application/json', 'X-CSRF-Token': this.csrfToken }
const response = await fetch(url, { method: 'POST', headers, body: JSON.stringify(data), credentials: 'same-origin' })
return response.json() }
refreshCsrfToken() { return this.initializeCsrfToken() } }
export function useApiClient() { const [apiClient] = useState(() => new ApiClient())
return apiClient }
|
🔑 认证安全策略
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
| class AuthManager { private tokenKey = 'auth_token' private refreshTokenKey = 'refresh_token'
setTokens(accessToken: string, refreshToken: string) { sessionStorage.setItem(this.tokenKey, accessToken) localStorage.setItem(this.refreshTokenKey, refreshToken) }
getAccessToken(): string | null { return sessionStorage.getItem(this.tokenKey) }
async refreshAccessToken(): Promise<string | null> { const refreshToken = localStorage.getItem(this.refreshTokenKey) if (!refreshToken) return null
try { const response = await fetch('/api/auth/refresh', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${refreshToken}` } })
if (response.ok) { const data = await response.json() this.setTokens(data.accessToken, data.refreshToken) return data.accessToken }
this.clearTokens() return null } catch (error) { this.clearTokens() return null } }
clearTokens() { sessionStorage.removeItem(this.tokenKey) localStorage.removeItem(this.refreshTokenKey) }
isTokenExpiringSoon(token: string): boolean { try { const payload = JSON.parse(atob(token.split('.')[1])) const expirationTime = payload.exp * 1000 const currentTime = Date.now() const timeUntilExpiry = expirationTime - currentTime
return timeUntilExpiry < 5 * 60 * 1000 } catch { return true } } }
export function useAuth() { const [authManager] = useState(() => new AuthManager()) const [isAuthenticated, setIsAuthenticated] = useState(false) const [user, setUser] = useState<User | null>(null)
useEffect(() => { const token = authManager.getAccessToken() if (token && !authManager.isTokenExpiringSoon(token)) { setIsAuthenticated(true) validateToken(token) } else if (token && authManager.isTokenExpiringSoon(token)) { authManager.refreshAccessToken().then(newToken => { if (newToken) { validateToken(newToken) } else { setIsAuthenticated(false) setUser(null) } }) } }, [])
const validateToken = async (token: string) => { try { const response = await fetch('/api/auth/verify', { headers: { 'Authorization': `Bearer ${token}` } })
if (response.ok) { const userData = await response.json() setUser(userData) setIsAuthenticated(true) } else { throw new Error('Token验证失败') } } catch { setIsAuthenticated(false) setUser(null) } }
return { isAuthenticated, user, authManager } }
|
🛠️ CI/CD前端质量门
1. 前端自动化流水线
🚀 GitHub Actions前端质量流水线
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
| name: Frontend Quality Gate
on: [push, pull_request]
jobs: quality-check: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4
- name: Setup Node.js uses: actions/setup-node@v4 with: node-version: '18' cache: 'npm'
- name: Install dependencies run: npm ci
- name: Run ESLint run: npm run lint
- name: Run TypeScript check run: npm run type-check
- name: Run unit tests run: npm run test:unit -- --coverage --watchAll=false
- name: Build application run: npm run build
- name: Run Lighthouse CI run: npm run lighthouse env: LHCI_GITHUB_APP_TOKEN: ${{ secrets.LHCI_GITHUB_APP_TOKEN }}
- name: Run visual regression tests run: npm run test:visual
- name: Bundle size check run: npm run bundle-analyzer env: BUNDLE_SIZE_LIMIT: 500kb
- name: Quality Gate Check run: | # 检查测试覆盖率 >= 80% # 检查Lighthouse分数 >= 90 # 检查Bundle大小不超过限制 # 检查无安全漏洞 echo "✅ 前端质量门检查通过"
deploy: needs: quality-check runs-on: ubuntu-latest if: github.ref == 'refs/heads/main' steps: - name: Deploy to Vercel run: npx vercel --prod env: VERCEL_TOKEN: ${{ secrets.VERCEL_TOKEN }}
|
2. 前端质量指标监控
📊 前端质量门禁指标
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| module.exports = { ci: { collect: { staticDistDir: './out', url: ['http://localhost:3000'] }, assert: { assertions: { 'categories:performance': ['error', { minScore: 0.9 }], 'categories:accessibility': ['error', { minScore: 0.9 }], 'categories:best-practices': ['error', { minScore: 0.9 }], 'categories:seo': ['error', { minScore: 0.9 }], 'categories:pwa': 'off' } } } }
|
📚 增强版Cursor前端使用指南
1. 零缺陷前端规则模板配置
🎯 高级前端规则模板
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| { "rules": [ { "name": "frontend-zero-defect-rules", "description": "前端零缺陷开发规则模板", "patterns": [ { "pattern": "const.*=.*\\(.*\\).*=>.*\\{", "replacement": "/**\n * $1\n *\n * @param {any} params - 参数说明\n * @returns {any} 返回值说明\n */\nconst $1 = ($2) => {\n // 🛡️ 参数校验\n if (!$2 || typeof $2 !== 'object') {\n throw new Error('参数无效')\n }\n\n try {\n // 🎯 核心逻辑\n $3\n } catch (error) {\n // 🚨 错误处理\n console.error('$1 执行失败:', error)\n throw error\n }\n}", "description": "自动生成带校验和错误处理的函数模板" }, { "pattern": "useEffect\\(\\(\\) => \\{", "replacement": "useEffect(() => {\n let isMounted = true\n\n const fetchData = async () => {\n try {\n // 🎯 异步数据获取\n $1\n } catch (error) {\n // 🚨 错误处理\n if (isMounted) {\n console.error('数据获取失败:', error)\n }\n }\n }\n\n fetchData()\n\n return () => {\n isMounted = false\n }\n}, [$2])", "description": "自动生成安全的useEffect模式" } ], "qualityGates": { "testCoverage": 80, "performance": 90, "accessibility": 85, "bundleSize": "500kb" } } ] }
|
🤖 前端AI提示词模板(零缺陷版)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
| # 零缺陷前端开发提示词
## 🎯 核心目标 生成零缺陷、可直接上线的现代化前端代码,符合企业级质量标准。
## 🛡️ 质量保障清单 - [x] **类型安全**:TypeScript严格模式,杜绝运行时错误 - [x] **用户体验**:响应式设计,无障碍访问,性能优化 - [x] **自测驱动**:组件测试先行,E2E测试保障 - [x] **性能优先**:零性能劣化,极致用户体验 - [x] **安全第一**:XSS防护,CSRF防护,认证安全
## 📋 前端代码审查标准 ### 功能完整性 ✅ - [x] 用户交互场景完整实现 - [x] 数据流转和状态管理正确 - [x] 错误处理和边界情况覆盖 - [x] 跨浏览器兼容性验证
### 用户体验质量 ✅ - [x] 响应式设计完美适配 - [x] 无障碍访问标准达到WCAG AA - [x] 性能指标符合Web Vitals标准 - [x] 视觉设计系统一致性
### 代码质量架构 ✅ - [x] TypeScript类型定义完整 - [x] React最佳实践严格遵循 - [x] 组件设计职责单一可复用 - [x] 测试覆盖率达到80%以上
## 🔧 自动代码生成规则
### 组件模板 ```typescript /** * $COMPONENT_NAME 组件 * * @description $COMPONENT_DESCRIPTION * @author AI Assistant * @since $CURRENT_DATE */ interface $COMPONENT_NAMEProps { /** $PROP_DESCRIPTION */ $PROP_NAME: $PROP_TYPE /** 可选属性 */ $OPTIONAL_PROP?: $OPTIONAL_TYPE /** 事件处理函数 */ on$EVENT?: ($PARAMS) => void }
export const $COMPONENT_NAME: React.FC<$COMPONENT_NAMEProps> = ({ $PROP_NAME, $OPTIONAL_PROP, on$EVENT, ...props }) => { // 🛡️ 参数校验 if (!$PROP_NAME) { throw new Error('$PROP_NAME 不能为空') }
// 🎯 组件逻辑 const handleEvent = useCallback(() => { on$EVENT?.($PARAMS) }, [on$EVENT])
return ( <$ELEMENT role="$ROLE" aria-label="$LABEL" onClick={handleEvent} className="$CLASS_NAME" {...props} > {/* 组件内容 */} </$ELEMENT> ) }
// 📝 默认导出组件 export default $COMPONENT_NAME
|
Hook模板
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
|
export function use$HOOK_NAME(options: $HOOK_OPTIONS = {}) { const { $REQUIRED_OPTION, $OPTIONAL_OPTION = $DEFAULT_VALUE } = options
if (!$REQUIRED_OPTION) { throw new Error('$REQUIRED_OPTION 不能为空') }
const [$STATE, set$STATE] = useState<$STATE_TYPE>($INITIAL_VALUE) const [loading, setLoading] = useState(false) const [error, setError] = useState<Error | null>(null)
const $MAIN_FUNCTION = useCallback(async () => { setLoading(true) setError(null)
try { const result = await $ASYNC_OPERATION set$STATE(result) } catch (err) { setError(err instanceof Error ? err : new Error('未知错误')) } finally { setLoading(false) } }, [$DEPENDENCIES])
useEffect(() => { return () => { } }, [])
return { $STATE, loading, error, $MAIN_FUNCTION } }
|
📊 前端质量指标监控
自动化指标收集
- Lighthouse分数:Performance >= 90, Accessibility >= 85
- Bundle大小:主Bundle <= 500KB, 总大小 <= 2MB
- 测试覆盖率:单元测试 >= 80%, E2E测试 >= 50%
- TypeScript错误:0个编译错误
- ESLint警告:0个错误,<= 5个警告
持续改进机制
- 性能监控数据:基于Lighthouse数据优化性能
- 用户反馈收集:基于用户行为数据改进体验
- A/B测试结果:基于测试数据优化功能
- 技术栈演进:跟进行业最佳实践更新技术栈
🎯 零缺陷前端开发工作流
第一阶段:需求分析与设计
- 用户研究:用户访谈,竞品分析,用研报告
- 交互设计:原型设计,用户流程图,交互规范
- 视觉设计:设计系统,组件库,视觉规范
- 技术方案:技术选型,架构设计,开发计划
第二阶段:组件驱动开发
- 设计系统搭建:基础组件,复合组件,页面模板
- Storybook开发:组件文档,交互演示,可视化测试
- 单元测试编写:组件测试,Hook测试,工具函数测试
- 集成测试验证:组件组合,数据流转,交互逻辑
第三阶段:质量保障验证
- 无障碍测试:键盘导航,屏幕阅读器,颜色对比度
- 性能测试:Lighthouse审计,Bundle分析,内存泄漏检测
- 跨浏览器测试:主流浏览器,移动端适配,兼容性修复
- 安全测试:XSS漏洞扫描,CSRF防护验证,认证安全检查
第四阶段:部署发布优化
- 构建优化:代码分割,资源压缩,CDN配置
- 部署策略:灰度发布,回滚方案,监控告警
- 性能监控:线上性能指标,错误追踪,用户行为分析
- 持续优化:基于数据分析,A/B测试,功能迭代
总结
这套增强版Cursor前端开发规则模板从根本上重构了现代化前端代码生成的质量保障体系:
🏆 核心价值(增强版)
🎨 用户体验至上
- 无障碍优先:WCAG 2.1 AA级标准,键盘导航,屏幕阅读器
- 响应式完美:移动优先,断点系统,触摸优化
- 性能极致:Lighthouse 90+,Bundle优化,加载加速
- 交互流畅:60fps渲染,动画优化,交互反馈
📊 质量指标体系
- 测试覆盖率:单元测试80% + 集成测试25% + E2E测试15%
- 性能基准:Lighthouse各指标 >= 90分
- Bundle大小:主Bundle <= 500KB,总大小 <= 2MB
- 无障碍覆盖:>= 85%的无障碍测试覆盖率
- TypeScript严格:0编译错误,完整类型覆盖
🔧 前端工程化工具链
- ESLint + Prettier:代码质量和格式化
- TypeScript:类型安全和开发体验
- Vite + Turbopack:快速构建和热重载
- Storybook:组件开发和文档化
- Playwright:端到端测试和视觉回归
📚 适用场景(现代化前端)
🖥️ 企业级Web应用开发
- SaaS平台:复杂业务逻辑,高并发访问的企业应用
- 管理后台:数据密集型,功能复杂的后台管理系统
- 电商平台:用户体验至上,性能要求极高的电商应用
- 社交平台:实时交互,海量数据的社交应用
🎯 现代化前端架构
- Next.js全栈:服务端渲染,API路由,性能优化
- 微前端架构:应用拆分,独立部署,技术栈灵活
- PWA应用:离线支持,推送通知,安装体验
- 低代码平台:可视化搭建,组件复用,快速开发
🚀 使用指南(最佳实践)
📋 实施步骤
- 技术栈评估:根据项目需求选择合适的技术栈
- 设计系统建设:建立统一的设计语言和组件库
- 开发规范制定:团队统一代码规范和开发流程
- 工具链配置:配置完整的开发和质量保障工具链
🎪 持续改进机制
- 性能数据驱动:基于Lighthouse和用户数据优化性能
- 用户反馈闭环:收集用户反馈持续改进体验
- 技术栈演进:跟进行业发展趋势更新技术栈
- 最佳实践沉淀:建立内部前端最佳实践知识库
🎊 对前端团队的影响
👥 开发体验提升
- 效率提升300%:AI辅助生成减少重复工作
- 质量保障100%:零缺陷代码生成,生产环境稳定性
- 学习曲线优化:现代化技术栈快速上手
- 技术债务清零:从源头杜绝技术债务积累
🏭 企业价值体现
- 用户体验倍增:现代化前端技术提升用户满意度
- 开发效率提升:组件化和工具化加速开发流程
- 维护成本降低:标准化和自动化减少维护工作量
- 创新能力增强:高质量基础支持快速业务创新
💡 核心理念
“前端开发不仅仅是代码,更是用户体验的匠心独运”
通过这套增强版规则模板,Cursor不再只是代码生成工具,而是:
- 🎨 用户体验卫士:从交互设计到性能优化全方位保障
- 🚀 开发效率加速器:组件化开发,自动化工具链
- 📚 技术标准传承者:现代化前端最佳实践标准化
- 🎯 质量指标指引者:明确的性能和质量目标
从今天开始,让每个前端功能都经过严格的用户体验验证,让每个界面都具备极致的交互体验! 🌟
🚀 零缺陷前端开发,从Cursor规则模板开始!