从本篇开始,我们进入编程应用阶段。前端开发是 AI 编程最成熟的场景之一——因为 HTML/CSS/JS 的语法相对固定,UI 组件化模式高度可预测,AI 能生成质量很高的代码。
一、为什么前端开发最适合 AI 编程
| 原因 |
说明 |
| 语法规则明确 |
HTML/CSS/JS 的语法和模式非常固定,AI 训练数据充足 |
| 可视化验证 |
生成结果在浏览器中即时可见,错误一目了然 |
| 组件化生态 |
React/Vue/Svelte 组件的接口模式非常适合 AI 生成 |
| 工具链成熟 |
Cursor/VS Code 对前端有专门的优化,Tailwind 类名 AI 也很擅长 |
| 重复模式多 |
CRUD 页面、表单、列表、模态框等模式高度重复 |
二、Cursor Cmd+K 生成页面
2.1 基础 HTML 页面生成
在空白 HTML 文件中按下 Cmd+K(Windows: Ctrl+K):
1 2 3 4 5 6
| 生成一个个人作品集的 landing page: - 顶部导航栏:Logo + 三个链接(作品、关于、联系) - Hero 区域:标题 + 副标题 + CTA 按钮 - 作品展示区:3x3 网格卡片 - 全部使用 Flexbox 布局,响应式设计 - 现代简约风格,主色调 #4F46E5
|
AI 会生成一份完整的 HTML 文件,包含内联 CSS 和 JavaScript:
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
| <!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>作品集</title> <style> * { margin: 0; padding: 0; box-sizing: border-box; } body { font-family: -apple-system, sans-serif; color: #1f2937; } .nav { display: flex; justify-content: space-between; align-items: center; padding: 1rem 2rem; background: white; box-shadow: 0 1px 3px rgba(0,0,0,0.1); } .nav-links { display: flex; gap: 2rem; } .nav-links a { text-decoration: none; color: #4b5563; font-weight: 500; transition: color 0.2s; } .nav-links a:hover { color: #4F46E5; } </style> </head> <body> <nav class="nav"> <div class="logo" style="font-weight:bold; font-size:1.5rem;">MyPortfolio</div> <div class="nav-links"> <a href="#works">作品</a> <a href="#about">关于</a> <a href="#contact">联系</a> </div> </nav> </body> </html>
|
2.2 纯 CSS 布局生成
如果只需要特定布局部分,也可以精确描述:
1 2 3 4 5
| 用 CSS Grid 生成一个三栏布局: - 左侧导航 250px - 中间内容区自适应 - 右侧边栏 300px - 粘性头部和页脚
|
AI 会生成针对性的 CSS 代码,包含 Grid 属性和响应式断点。
三、React/Next.js 项目实战
3.1 用 AI 搭建项目脚手架
使用 Claude Code 创建 Next.js 项目:
1 2
| 创建一个 Next.js 14 项目,使用 App Router, 集成 Tailwind CSS,包含首页、产品详情页、关于页面。
|
Claude Code 会依次执行:
npx create-next-app@latest 创建项目
- 配置
tailwind.config.js
- 生成
app/page.tsx、app/products/[id]/page.tsx、app/about/page.tsx
- 创建共享组件目录
components/
- 初始化 Git 仓库
3.2 生成 React 组件
在 Cursor 中用 Cmd+K 创建组件:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| interface Product { id: number; title: string; price: number; rating: number; image: string; }
export function ProductCard({ product }: { product: Product }) { return ( <div className="group cursor-pointer rounded-xl border p-4 transition-all hover:shadow-lg hover:-translate-y-1"> <img src={product.image} alt={product.title} loading="lazy" className="h-48 w-full object-contain mb-4" /> <h3 className="font-semibold text-lg truncate">{product.title}</h3> <p className="text-blue-600 font-bold mt-1">{product.price}</p> </div> ); }
|
3.3 生成 API 数据获取
用 ChatGPT 或 Cursor 生成数据请求逻辑:
1 2 3 4 5
| 生成一个 React Hook,从 API 获取产品列表: - 支持分页 - 有 loading 和 error 状态 - 支持搜索过滤 - 使用 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
| interface UseFetchResult<T> { data: T | null; loading: boolean; error: string | null; refetch: () => void; }
function useFetch<T>(url: string): UseFetchResult<T> { const [data, setData] = useState<T | null>(null); const [loading, setLoading] = useState(true); const [error, setError] = useState<string | null>(null);
const fetchData = useCallback(async () => { setLoading(true); setError(null); try { const res = await fetch(url); if (!res.ok) throw new Error(`HTTP ${res.status}`); const json = await res.json(); setData(json); } catch (e) { setError(e instanceof Error ? e.message : '未知错误'); } finally { setLoading(false); } }, [url]);
useEffect(() => { fetchData(); }, [fetchData]); return { data, loading, error, refetch: fetchData }; }
|
3.4 状态管理自动生成
1 2 3 4 5
| 使用 Zustand 创建购物车 Store: - 添加/删除商品 - 更新数量 - 计算总价 - 持久化到 localStorage
|
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
| import { create } from 'zustand'; import { persist } from 'zustand/middleware';
interface CartItem { id: number; name: string; price: number; quantity: number; }
interface CartStore { items: CartItem[]; addItem: (item: Omit<CartItem, 'quantity'>) => void; removeItem: (id: number) => void; updateQuantity: (id: number, qty: number) => void; total: () => number; clear: () => void; }
export const useCartStore = create<CartStore>()( persist( (set, get) => ({ items: [], addItem: (item) => { const items = get().items; const existing = items.find(i => i.id === item.id); if (existing) { set({ items: items.map(i => i.id === item.id ? { ...i, quantity: i.quantity + 1 } : i )}); } else { set({ items: [...items, { ...item, quantity: 1 }] }); } }, removeItem: (id) => set({ items: get().items.filter(i => i.id !== id) }), updateQuantity: (id, qty) => set({ items: get().items.map(i => i.id === id ? { ...i, quantity: qty } : i) }), total: () => get().items.reduce((sum, i) => sum + i.price * i.quantity, 0), clear: () => set({ items: [] }), }), { name: 'cart-storage' } ) );
|
四、AI 辅助前端开发最佳实践
4.1 渐进式生成
不要一次让 AI 生成整个页面。分步生成效果更好:
1 2 3 4 5
| 第1步:生成 HTML 骨架结构 第2步:添加 CSS 样式 第3步:实现交互逻辑 第4步:连接真实 API 第5步:响应式适配
|
每个步骤独立 Prompt,方便局部修改和调整。
4.2 善用 .cursorrules
在前端项目中创建 .cursorrules,让 AI 遵循你的技术栈和风格:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| 你是一名资深的 React 前端开发者。
技术栈: - React 18 + TypeScript - Next.js 14 (App Router) - Tailwind CSS - Zustand 状态管理 - React Query 数据获取
编码规范: - 使用函数组件 + Hooks - 组件文件使用 PascalCase - 优先使用 Tailwind 类名,避免内联 style - 所有组件导出使用默认导出 - 关键交互添加过渡动画
|
五、常见陷阱与应对
| AI 生成的问题 |
表现 |
解决 |
| 过度依赖客户端 JS |
不使用 SSR/SSG 特性 |
检查数据获取时机 |
| 缺乏错误处理 |
API 请求没有 try-catch |
明确要求添加错误状态 |
| 可访问性缺失 |
缺少 aria 标签和键盘事件 |
添加 a11y 要求到 Prompt |
| 不必要的库引用 |
为了一个函数引入整个库 |
审查 dependencies 后再安装 |
| 类型定义不完整 |
any 类型过多 |
要求严格的 TypeScript 类型 |
六、响应式设计实战
1 2 3 4 5 6
| 生成一个产品列表页面: - 桌面端:4 列网格 - 平板端:2 列网格 - 手机端:1 列列表 - 图片比例一致,懒加载 - 价格标签在右下角吸底
|
AI 结合 Tailwind 的响应式断点生成:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| export function ProductGrid({ products }: { products: Product[] }) { return ( <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 md:gap-6 p-4"> {products.map(product => ( <div key={product.id} className="relative bg-white rounded-lg shadow-sm hover:shadow-md transition-shadow"> <img src={product.image} alt={product.name} loading="lazy" className="w-full h-48 object-cover rounded-t-lg" /> <div className="p-3"> <h3 className="font-medium text-gray-900 truncate">{product.name}</h3> <span className="absolute bottom-3 right-3 bg-blue-600 text-white px-2 py-1 rounded-md text-sm"> ¥{product.price} </span> </div> </div> ))} </div> ); }
|
本章小结
- 前端是 AI 编程最成熟的领域,HTML/CSS/JS 的固定模式让 AI 表现优异
- Cmd+K 适合单文件生成,Claude Code 适合项目级脚手架
- React 组件化生态非常适合 AI 辅助开发,可自动生成 Hook、Store、类型定义
- 分步生成比一次性生成效果更好,每步可独立调整
- 善用 .cursorrules 约束 AI 的技术栈和风格
- 审查 AI 生成代码时重点关注:过度 JS 依赖、错误处理缺失、可访问性、不必要的依赖
下一篇看如何用 AI 辅助后端开发。