nextjs-shadcn-builder
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseNext.js + shadcn/ui Builder & Migration Tool
Next.js + shadcn/ui 构建与迁移工具
Build production-grade Next.js applications or systematically migrate existing frontends to Next.js + shadcn/ui following strict design principles and best practices.
遵循严格的设计原则与最佳实践,构建生产级Next.js应用,或系统化地将现有前端项目迁移至Next.js + shadcn/ui技术栈。
Overview
概述
This skill handles two primary workflows:
- Creating New Next.js Applications - Initialize projects with Next.js 15+ (App Router), shadcn/ui, and proper design system setup
- Migrating Existing Frontends - Analyze any frontend codebase (React, Vue, Angular, vanilla JS) and systematically convert to Next.js + shadcn/ui
Core Philosophy: 100% adherence to shadcn/ui design principles:
- CSS variables for all theming (colors, spacing, typography)
- Standard shadcn/ui components only (no custom UI components)
- No hardcoded values (colors, spacing, fonts)
- Consistent design tokens across the application
- Mobile-first responsive design for all devices (phone, tablet, desktop)
- WCAG 2.1 Level AA accessibility compliance
- Best practices from https://ui.shadcn.com
本工具支持两大核心工作流:
- 创建全新Next.js应用 - 初始化基于Next.js 15+(App Router)、shadcn/ui的项目,并完成设计系统的正确配置
- 迁移现有前端项目 - 分析任意前端代码库(React、Vue、Angular、原生JS),并系统化转换为Next.js + shadcn/ui技术栈
核心理念:100%遵循shadcn/ui设计原则:
- 所有主题配置使用CSS变量(颜色、间距、排版)
- 仅使用标准shadcn/ui组件(禁止自定义UI组件)
- 无硬编码值(颜色、间距、字体均不允许硬编码)
- 全应用保持一致的设计令牌
- 所有设备采用移动端优先的响应式设计(手机、平板、桌面端)
- 符合WCAG 2.1 Level AA无障碍标准
- 遵循https://ui.shadcn.com提供的最佳实践
Workflow Decision Tree
工作流决策树
User Request
├─ Creating New Next.js App
│ └─ Follow "Creating New Application" workflow (Phase 3 onwards)
│
└─ Migrating Existing Codebase
├─ Phase 1: Codebase Analysis
├─ Phase 2: Migration Planning
├─ Phase 3: Next.js + shadcn Setup
├─ Phase 4: Systematic Conversion
└─ Phase 5: Verification & Cleanup用户请求
├─ 创建全新Next.js应用
│ └─ 遵循「创建新应用」工作流(从第3阶段开始)
│
└─ 迁移现有代码库
├─ 阶段1:代码库分析
├─ 阶段2:迁移规划
├─ 阶段3:Next.js + shadcn环境搭建
├─ 阶段4:系统化转换
└─ 阶段5:验证与清理High-Level Workflow for Migration
迁移工作流概览
Phase 1: Codebase Analysis
阶段1:代码库分析
Automated analysis of existing frontend to understand scope and complexity.
Steps:
- Framework and version detection
- Component inventory and categorization
- Hardcoded value detection (colors, spacing, custom components)
- Styling approach analysis (CSS, SCSS, CSS-in-JS, Tailwind, etc.)
- State management and routing pattern identification
- Generate comprehensive analysis report
Deliverables:
- Framework analysis report
- Component inventory (JSON)
- Hardcoded values report
- Complexity assessment
自动化分析现有前端项目,明确迁移范围与复杂度。
步骤:
- 框架与版本检测
- 组件盘点与分类
- 硬编码值检测(颜色、间距、自定义组件)
- 样式方案分析(CSS、SCSS、CSS-in-JS、Tailwind等)
- 状态管理与路由模式识别
- 生成综合分析报告
交付物:
- 框架分析报告
- 组件清单(JSON格式)
- 硬编码值检测报告
- 复杂度评估结果
Phase 2: Migration Planning
阶段2:迁移规划
Create systematic conversion plan with prioritized batches.
Steps:
- Map existing components to shadcn/ui equivalents
- Identify components requiring custom development
- Organize conversion into batches (5-10 components per batch)
- Assess risk and complexity per batch
- Create detailed migration plan
Deliverables:
- Component mapping table
- Batched conversion plan
- Risk assessment
- Estimated complexity per component
创建系统化的转换计划,按优先级划分批次。
步骤:
- 将现有组件映射至对应的shadcn/ui组件
- 识别需要自定义开发的组件
- 将转换任务划分为多个批次(每批次5-10个组件)
- 评估每批次的风险与复杂度
- 创建详细的迁移计划
交付物:
- 组件映射表
- 分批次转换计划
- 风险评估报告
- 各组件的复杂度预估
Phase 3: Next.js + shadcn Setup
阶段3:Next.js + shadcn环境搭建
Initialize Next.js infrastructure alongside or replacing existing codebase.
Steps:
- Check/install shadcn MCP server for documentation access
- Initialize Next.js 15+ with App Router and TypeScript
- Install and configure Tailwind CSS
- Run shadcn/ui initialization
- Set up CSS variables and design tokens
- Configure path aliases (@/)
- Install essential shadcn components
- Create design system documentation
Deliverables:
- Configured Next.js project
- Design token system (CSS variables)
- Component library setup
- Path aliases configured
初始化Next.js基础设施,可与现有代码库并行运行或直接替换。
步骤:
- 检查/安装shadcn MCP服务器以访问文档
- 初始化Next.js 15+项目,启用App Router与TypeScript
- 安装并配置Tailwind CSS
- 运行shadcn/ui初始化命令
- 配置CSS变量与设计令牌
- 设置路径别名(@/)
- 安装核心shadcn组件
- 创建设计系统文档
交付物:
- 已配置完成的Next.js项目
- 设计令牌系统(CSS变量)
- 组件库环境
- 已配置的路径别名
Phase 4: Systematic Conversion
阶段4:系统化转换
Convert components batch by batch with testing after each batch.
Steps:
- Batch 1: Layout & Structure (Header, Footer, Layout wrappers)
- Batch 2: Simple UI Components (Buttons, Cards, Badges, Alerts)
- Batch 3: Form Components (Inputs, Selects, Checkboxes, Forms)
- Batch 4: Complex Components (Tables, Dialogs, Command Menus, Data visualizations)
- Batch 5: Styling Standardization (Remove hardcoded values, apply CSS variables)
- Batch 6: Pages & Routes (Convert pages, set up Next.js routing)
Per Batch Workflow:
- Select 5-10 related components
- Use MCP to find appropriate shadcn components
- Convert components following shadcn patterns
- Replace hardcoded values with CSS variables
- Test functionality
- Verify visual consistency
- Move to next batch
Deliverables:
- Migrated components (batch by batch)
- Updated styling with CSS variables
- Next.js App Router pages
- Passing tests per batch
按批次转换组件,每批次完成后进行测试。
步骤:
- 批次1:布局与结构(头部、底部、布局容器)
- 批次2:简单UI组件(按钮、卡片、徽章、提示框)
- 批次3:表单组件(输入框、选择器、复选框、表单)
- 批次4:复杂组件(表格、对话框、命令菜单、数据可视化)
- 批次5:样式标准化(移除硬编码值,应用CSS变量)
- 批次6:页面与路由(转换页面,配置Next.js路由)
每批次工作流:
- 选择5-10个相关组件
- 使用MCP查找合适的shadcn组件
- 遵循shadcn模式转换组件
- 用CSS变量替代硬编码值
- 测试功能完整性
- 验证视觉一致性
- 进入下一批次
交付物:
- 已迁移的组件(按批次交付)
- 已更新为CSS变量的样式
- Next.js App Router页面
- 每批次均通过测试
Phase 5: Verification & Cleanup
阶段5:验证与清理
Final testing, optimization, and old code removal.
Steps:
- Run full test suite
- Visual regression testing
- Responsive design testing (mobile, tablet, desktop)
- Performance audit
- Accessibility audit (WCAG 2.1 Level AA compliance)
- Remove old framework code
- Documentation updates
- Generate completion report
Deliverables:
- Test results
- Responsive design verification report
- Performance metrics
- Accessibility audit report (WCAG 2.1 AA)
- Clean codebase
- Migration summary
最终测试、优化与旧代码移除。
步骤:
- 运行完整测试套件
- 视觉回归测试
- 响应式设计测试(移动端、平板、桌面端)
- 性能审计
- 无障碍审计(WCAG 2.1 Level AA合规性)
- 移除旧框架代码
- 更新文档
- 生成完成报告
交付物:
- 测试结果
- 响应式设计验证报告
- 性能指标
- 无障碍审计报告(WCAG 2.1 AA)
- 清理后的代码库
- 迁移总结
Phase 1: Codebase Analysis (Detailed Instructions)
阶段1:代码库分析(详细说明)
1.1 Framework Detection
1.1 框架检测
Run the automated analysis script:
bash
python ./scripts/analyze-codebase.py /path/to/existing/codebaseThis script will:
- Detect framework (React, Vue, Angular, Svelte, vanilla JS, etc.)
- Identify framework version
- Detect build tool (Vite, Webpack, Parcel, etc.)
- Find package.json dependencies
- Map directory structure
Output: with framework metadata
codebase-analysis.json运行自动化分析脚本:
bash
python ./scripts/analyze-codebase.py /path/to/existing/codebase该脚本将:
- 检测框架类型(React、Vue、Angular、Svelte、原生JS等)
- 识别框架版本
- 检测构建工具(Vite、Webpack、Parcel等)
- 查找package.json中的依赖
- 映射目录结构
输出: ,包含框架元数据
codebase-analysis.json1.2 Component Inventory
1.2 组件盘点
The analysis script automatically generates a component inventory including:
- Component name and file path
- Component type (functional, class, Vue SFC, etc.)
- Props/inputs
- State usage
- Child components
- External dependencies
Output:
component-inventory.jsonExample structure:
json
{
"components": [
{
"name": "UserCard",
"path": "src/components/UserCard.tsx",
"type": "functional",
"complexity": "simple",
"shadcn_equivalent": "Card",
"hardcoded_values": ["#3b82f6", "16px padding"],
"dependencies": ["react", "styled-components"]
}
]
}分析脚本会自动生成组件清单,包含:
- 组件名称与文件路径
- 组件类型(函数式、类组件、Vue单文件组件等)
- 属性/输入参数
- 状态使用情况
- 子组件
- 外部依赖
输出:
component-inventory.json示例结构:
json
{
"components": [
{
"name": "UserCard",
"path": "src/components/UserCard.tsx",
"type": "functional",
"complexity": "simple",
"shadcn_equivalent": "Card",
"hardcoded_values": ["#3b82f6", "16px padding"],
"dependencies": ["react", "styled-components"]
}
]
}1.3 Hardcoded Value Detection
1.3 硬编码值检测
Run the detection script:
bash
bash ./scripts/detect-hardcoded-values.sh /path/to/existing/codebaseThis script detects:
- Hardcoded colors: ,
#hex,rgb(),rgba(), color nameshsl() - Inline spacing: ,
margin: 20pxpadding: 1rem - Custom font declarations: non-standard fonts
- Magic numbers: arbitrary values in components
- Inline styles:
style={{...}} - Non-standard patterns: CSS-in-JS, styled-components that should be Tailwind
Output: with violations grouped by category
hardcoded-values-report.md运行检测脚本:
bash
bash ./scripts/detect-hardcoded-values.sh /path/to/existing/codebase该脚本会检测:
- 硬编码颜色:、
#hex、rgb()、rgba()、颜色名称hsl() - 内联间距:、
margin: 20pxpadding: 1rem - 自定义字体声明:非标准字体
- 魔法数字:组件中的任意数值
- 内联样式:
style={{...}} - 非标准模式:应替换为Tailwind的CSS-in-JS、styled-components代码
输出: ,按类别分组展示违规内容
hardcoded-values-report.md1.4 Generate Analysis Report
1.4 生成分析报告
Run the report generator:
bash
python ./scripts/generate-migration-report.pyThis combines all analysis data into a comprehensive markdown report:
Output:
migration-analysis-report.mdmarkdown
undefined运行报告生成脚本:
bash
python ./scripts/generate-migration-report.py该脚本将所有分析数据整合为一份综合Markdown报告:
输出:
migration-analysis-report.mdmarkdown
undefinedFrontend Migration Analysis Report
前端迁移分析报告
Executive Summary
执行摘要
[One-paragraph overview: framework, size, complexity]
[一段概述:框架类型、项目规模、复杂度]
Current State Analysis
当前状态分析
- Framework: React 18.2.0
- Build Tool: Vite 4.3.0
- Component Count: 47 components
- Styling: styled-components + custom CSS
- State Management: Redux Toolkit
- Routing: React Router v6
- 框架:React 18.2.0
- 构建工具:Vite 4.3.0
- 组件数量:47个
- 样式方案:styled-components + 自定义CSS
- 状态管理:Redux Toolkit
- 路由:React Router v6
Hardcoded Values Detected
检测到的硬编码值
- Colors: 142 instances across 34 files
- Spacing: 89 instances across 28 files
- Custom fonts: 3 non-standard fonts
- Inline styles: 67 instances
- 颜色:34个文件中存在142处
- 间距:28个文件中存在89处
- 自定义字体:3种非标准字体
- 内联样式:67处
Component Categorization
组件分类
- Simple (shadcn mapping exists): 28 components
- Moderate (requires adaptation): 13 components
- Complex (custom development needed): 6 components
- 简单(存在shadcn映射):28个组件
- 中等(需要适配):13个组件
- 复杂(需要自定义开发):6个组件
Recommended Migration Plan
推荐迁移计划
- Phase 3: Setup Next.js + shadcn infrastructure
- Phase 4.1: Convert layout components (Header, Footer, Layout)
- Phase 4.2: Convert simple UI (Button, Card, Badge → shadcn equivalents)
- Phase 4.3: Convert forms (Input, Select → shadcn/ui Form components)
- Phase 4.4: Convert complex components (DataTable, Charts)
- Phase 4.5: Styling standardization (CSS variables)
- Phase 4.6: Pages and routing
- Phase 5: Verification and cleanup
- 阶段3:搭建Next.js + shadcn基础设施
- 阶段4.1:转换布局组件(头部、底部、布局容器)
- 阶段4.2:转换简单UI组件(按钮、卡片、徽章 → 对应shadcn组件)
- 阶段4.3:转换表单组件(输入框、选择器 → shadcn/ui表单组件)
- 阶段4.4:转换复杂组件(数据表格、图表)
- 阶段4.5:样式标准化(CSS变量)
- 阶段4.6:页面与路由转换
- 阶段5:验证与清理
Estimated Effort
预估工作量
- Total Components: 47
- Batches: 9-10 batches
- Complexity: Moderate
---- 总组件数:47个
- 批次数量:9-10批
- 复杂度:中等
---Phase 2: Migration Planning (Detailed Instructions)
阶段2:迁移规划(详细说明)
2.1 Component Mapping Strategy
2.1 组件映射策略
Review the and create a mapping table using the shadcn component reference.
component-inventory.jsonVERY IMPORTANT: Use MCP to discover shadcn components
Before mapping, check if shadcn MCP server is available:
bash
undefined查看,并使用shadcn组件参考创建映射表。
component-inventory.json非常重要:使用MCP查找shadcn组件
映射前,检查shadcn MCP服务器是否可用:
bash
undefinedCheck if MCP server is available
检查MCP服务器是否可用
Try accessing https://ui.shadcn.com/docs/mcp
If MCP is not available, install it:
```bash
npx shadcn@latest mcp init --client claudeUse MCP to query available components:
- "What shadcn components are available for buttons?"
- "Show me form components in shadcn"
- "What's the shadcn equivalent of a modal/dialog?"
- "Available data display components in shadcn"
Component Mapping Table Template:
| Existing Component | shadcn Equivalent | Complexity | Priority | Notes |
|---|---|---|---|---|
| CustomButton | Button | Low | 1 | Props mostly compatible |
| Modal | Dialog | Medium | 2 | Different API, uses Radix |
| DataTable | Table + DataTable | High | 3 | Requires custom hooks |
| Dropdown | DropdownMenu | Low | 1 | Direct mapping |
| DatePicker | Calendar + Popover | Medium | 2 | Composition pattern |
Load framework-specific migration guide:
- For React: Read
./references/react-to-nextjs.md - For Vue: Read
./references/vue-to-nextjs.md - For Angular: Read
./references/angular-to-nextjs.md - For styling: Read
./references/styling-migration.md
若MCP不可用,执行安装命令:
```bash
npx shadcn@latest mcp init --client claude使用MCP查询可用组件:
- "shadcn有哪些按钮组件?"
- "展示shadcn的表单组件"
- "shadcn中与模态框对应的组件是什么?"
- "shadcn提供的数据展示组件有哪些?"
组件映射表示例:
| 现有组件 | shadcn对应组件 | 复杂度 | 优先级 | 备注 |
|---|---|---|---|---|
| CustomButton | Button | 低 | 1 | 属性基本兼容 |
| Modal | Dialog | 中 | 2 | API不同,基于Radix实现 |
| DataTable | Table + DataTable | 高 | 3 | 需要自定义Hook |
| Dropdown | DropdownMenu | 低 | 1 | 直接映射 |
| DatePicker | Calendar + Popover | 中 | 2 | 组合模式 |
加载框架专属迁移指南:
- React:查看
./references/react-to-nextjs.md - Vue:查看
./references/vue-to-nextjs.md - Angular:查看
./references/angular-to-nextjs.md - 样式:查看
./references/styling-migration.md
2.2 Batch Organization
2.2 批次组织
Organize components into batches following these principles:
Batching Strategy:
- Group by type (layout, forms, data display, navigation)
- Simple to complex (start with easy wins)
- Dependency order (convert dependencies first)
- Batch size: 5-10 components per batch
Example Batch Plan:
Batch 1: Layout & Structure (Priority: Critical)
- Header
- Footer
- MainLayout
- Container
- Sidebar
Batch 2: Simple UI Components (Priority: High)
- Button → shadcn Button
- Card → shadcn Card
- Badge → shadcn Badge
- Alert → shadcn Alert
- Avatar → shadcn Avatar
Batch 3: Form Components (Priority: High)
- Input → shadcn Input
- Select → shadcn Select
- Checkbox → shadcn Checkbox
- RadioGroup → shadcn RadioGroup
- Form validation → shadcn Form + react-hook-form
Batch 4: Navigation (Priority: Medium)
- NavBar → shadcn NavigationMenu
- Breadcrumbs → shadcn Breadcrumb
- Tabs → shadcn Tabs
- Pagination → shadcn Pagination
Batch 5: Data Display (Priority: Medium)
- Table → shadcn Table
- DataGrid → shadcn DataTable (with sorting, filtering)
- List → shadcn custom composition
- Accordion → shadcn Accordion
Batch 6: Overlays & Modals (Priority: Medium)
- Modal → shadcn Dialog
- Tooltip → shadcn Tooltip
- Popover → shadcn Popover
- DropdownMenu → shadcn DropdownMenu
Batch 7: Complex Components (Priority: Low)
- Charts → shadcn Charts (Recharts integration)
- Calendar/DatePicker → shadcn Calendar
- CommandPalette → shadcn Command
- DataVisualization → Custom with shadcn primitives
Batch 8: Styling Standardization (Priority: Critical)
- Extract all hardcoded colors → CSS variables
- Convert spacing to Tailwind classes
- Standardize typography
- Apply theme system consistently
Batch 9: Pages & Routing (Priority: Critical)
- Convert pages to Next.js App Router
- Set up layouts with Next.js layout.tsx
- Implement routing patterns
- Add loading and error states
遵循以下原则将组件划分为批次:
批次划分策略:
- 按类型分组(布局、表单、数据展示、导航)
- 从简单到复杂(先完成易于转换的组件)
- 按依赖顺序(先转换被依赖的组件)
- 批次规模:每批次5-10个组件
示例批次计划:
批次1:布局与结构(优先级:关键)
- Header
- Footer
- MainLayout
- Container
- Sidebar
批次2:简单UI组件(优先级:高)
- Button → shadcn Button
- Card → shadcn Card
- Badge → shadcn Badge
- Alert → shadcn Alert
- Avatar → shadcn Avatar
批次3:表单组件(优先级:高)
- Input → shadcn Input
- Select → shadcn Select
- Checkbox → shadcn Checkbox
- RadioGroup → shadcn RadioGroup
- 表单验证 → shadcn Form + react-hook-form
批次4:导航组件(优先级:中)
- NavBar → shadcn NavigationMenu
- Breadcrumbs → shadcn Breadcrumb
- Tabs → shadcn Tabs
- Pagination → shadcn Pagination
批次5:数据展示组件(优先级:中)
- Table → shadcn Table
- DataGrid → shadcn DataTable(支持排序、筛选)
- List → 基于shadcn原语自定义组合
- Accordion → shadcn Accordion
批次6:浮层与模态框(优先级:中)
- Modal → shadcn Dialog
- Tooltip → shadcn Tooltip
- Popover → shadcn Popover
- DropdownMenu → shadcn DropdownMenu
批次7:复杂组件(优先级:低)
- Charts → shadcn Charts(集成Recharts)
- Calendar/DatePicker → shadcn Calendar
- CommandPalette → shadcn Command
- DataVisualization → 基于shadcn原语自定义
批次8:样式标准化(优先级:关键)
- 提取所有硬编码颜色 → 转换为CSS变量
- 将间距转换为Tailwind类
- 标准化排版
- 统一应用主题系统
批次9:页面与路由(优先级:关键)
- 将页面转换为Next.js App Router格式
- 使用Next.js layout.tsx配置布局
- 实现路由模式
- 添加加载与错误状态
2.3 Risk Assessment
2.3 风险评估
For each batch, identify risks:
- API Differences: Components with significantly different APIs
- Missing Features: Features in old components not in shadcn
- State Management: Complex state that needs refactoring
- Dependencies: External libraries that need replacement
- Custom Logic: Business logic tightly coupled to UI
Risk Mitigation:
- Document API differences before conversion
- Create adapter/wrapper components when needed
- Write tests before migration
- Keep old components temporarily during transition
为每个批次识别风险:
- API差异:API差异较大的组件
- 功能缺失:旧组件具备但shadcn组件没有的功能
- 状态管理:需要重构的复杂状态
- 依赖项:需要替换的外部库
- 自定义逻辑:与UI紧密耦合的业务逻辑
风险缓解方案:
- 转换前记录API差异
- 必要时创建适配器/包装组件
- 迁移前编写测试
- 过渡期间暂时保留旧组件
2.4 Create Detailed Migration Plan
2.4 创建详细迁移计划
Generate a detailed plan document:
migration-plan.mdmarkdown
undefined生成详细的计划文档:
migration-plan.mdmarkdown
undefinedNext.js + shadcn Migration Plan
Next.js + shadcn迁移计划
Project: [Project Name]
项目:[项目名称]
Date: [Current Date]
日期:[当前日期]
Estimated Timeline: [X batches]
预估时间线:[X个批次]
Migration Strategy
迁移策略
Approach
方法
- Incremental migration with parallel running old and new code
- Batch-based conversion (5-10 components per batch)
- Test after each batch before proceeding
- Feature flag new components during transition
- 增量迁移,旧代码与新代码并行运行
- 基于批次的转换(每批次5-10个组件)
- 每批次完成后测试,再进行下一批次
- 过渡期间通过功能标志启用新组件
Success Criteria
成功标准
- All components use shadcn/ui or shadcn patterns
- Zero hardcoded colors/spacing (CSS variables only)
- 100% TypeScript coverage
- Passing test suite
- Lighthouse score >= 90
- No accessibility violations
- 所有组件使用shadcn/ui或shadcn模式
- 无硬编码颜色/间距(仅使用CSS变量)
- 100% TypeScript覆盖率
- 测试套件全部通过
- Lighthouse评分≥90
- 无无障碍违规
Detailed Batch Plan
详细批次计划
[Include all batches from 2.2 with specific components listed]
[包含2.2中的所有批次及具体组件]
Timeline
时间线
Batch 1: Layout & Structure (Days 1-2)
Batch 2: Simple UI (Days 3-4)
[etc.]
批次1:布局与结构(第1-2天)
批次2:简单UI组件(第3-4天)
[以此类推]
Notes and Considerations
注意事项
[Any special requirements, blockers, or dependencies]
---[任何特殊要求、阻塞点或依赖项]
---Phase 3: Next.js + shadcn Setup (Detailed Instructions)
阶段3:Next.js + shadcn环境搭建(详细说明)
3.1 Check/Install shadcn MCP Server
3.1 检查/安装shadcn MCP服务器
CRITICAL: Always use MCP for shadcn component discovery
-
Check if MCP server is accessible:
- Try to access documentation at
https://ui.shadcn.com/docs/mcp - Check if you can query shadcn components via MCP
- Try to access documentation at
-
If not available, install MCP server:
bash
npx shadcn@latest mcp init --client claudeThis enables:
- Real-time shadcn documentation access
- Component discovery and search
- Block and chart template discovery
- Theme and design token reference
Using MCP during development:
- "What components are available for [use case]?"
- "Show me the props for shadcn Button"
- "Available chart types in shadcn"
- "How to use shadcn Form with validation"
关键:始终使用MCP查找shadcn组件
-
检查MCP服务器是否可访问:
- 尝试访问文档
https://ui.shadcn.com/docs/mcp - 检查是否可通过MCP查询shadcn组件
- 尝试访问文档
-
若不可用,安装MCP服务器:
bash
npx shadcn@latest mcp init --client claude安装后支持:
- 实时访问shadcn文档
- 组件查找与搜索
- 区块与图表模板查找
- 主题与设计令牌参考
开发中使用MCP:
- "[使用场景]对应的shadcn组件有哪些?"
- "展示shadcn Button的属性"
- "shadcn支持的图表类型"
- "如何结合shadcn Form实现验证"
3.2 Initialize Next.js Project
3.2 初始化Next.js项目
Run the initialization script:
bash
bash ./scripts/init-nextjs-shadcn.sh [project-name]Or manually initialize:
bash
undefined运行初始化脚本:
bash
bash ./scripts/init-nextjs-shadcn.sh [project-name]或手动初始化:
bash
undefinedCheck Node.js version (18+ required)
检查Node.js版本(需要18+)
node -v
node -v
Create Next.js project with App Router
创建带App Router的Next.js项目
npx create-next-app@latest [project-name]
--typescript
--tailwind
--app
--src-dir
--import-alias "@/*"
--no-turbopack
--typescript
--tailwind
--app
--src-dir
--import-alias "@/*"
--no-turbopack
cd [project-name]
undefinednpx create-next-app@latest [project-name]
--typescript
--tailwind
--app
--src-dir
--import-alias "@/*"
--no-turbopack
--typescript
--tailwind
--app
--src-dir
--import-alias "@/*"
--no-turbopack
cd [project-name]
undefined3.3 Install and Configure shadcn/ui
3.3 安装并配置shadcn/ui
bash
undefinedbash
undefinedInitialize shadcn/ui
初始化shadcn/ui
npx shadcn@latest init
npx shadcn@latest init
Configuration prompts:
配置提示:
- TypeScript: Yes
- TypeScript:是
- Style: Default
- 样式:默认
- Base color: Choose from slate/gray/zinc/neutral/stone
- 基础颜色:从slate/gray/zinc/neutral/stone中选择
- CSS variables: Yes (CRITICAL - required for theming)
- CSS变量:是(关键 - 主题定制必需)
- Import alias: @/components
- 导入别名:@/components
This creates:
- `components.json` config file
- `lib/utils.ts` with cn() helper
- Updated `tailwind.config.ts` with shadcn theme
- CSS variables in `app/globals.css`
执行后会创建:
- `components.json`配置文件
- `lib/utils.ts`,包含cn()工具函数
- 已更新的`tailwind.config.ts`,集成shadcn主题
- `app/globals.css`中的CSS变量3.4 Configure Design Tokens (CSS Variables)
3.4 配置设计令牌(CSS变量)
VERY IMPORTANT: All theming MUST use CSS variables
Color Format: OKLCH (Recommended)
This skill uses OKLCH (OKLab Lightness Chroma Hue) color space instead of HSL for better perceptual uniformity and color accuracy.
OKLCH Benefits:
- Perceptually uniform (equal changes = equal perceived differences)
- Better gradient interpolation
- More predictable lightness
- Better for accessibility (more accurate contrast ratios)
Edit to define your design system:
app/globals.csscss
@tailwind base;
@tailwind components;
@tailwind utilities;
@layer base {
:root {
--radius: 0.65rem;
/* Background - Pure white */
--background: 1 0 0;
--foreground: 0.141 0.005 285.823;
/* Card */
--card: 1 0 0;
--card-foreground: 0.141 0.005 285.823;
/* Popover */
--popover: 1 0 0;
--popover-foreground: 0.141 0.005 285.823;
/* Primary - Warm orange */
--primary: 0.646 0.222 41.116;
--primary-foreground: 0.98 0.016 73.684;
/* Secondary - Light purple-gray */
--secondary: 0.967 0.001 286.375;
--secondary-foreground: 0.21 0.006 285.885;
/* Muted - Subtle elements */
--muted: 0.967 0.001 286.375;
--muted-foreground: 0.552 0.016 285.938;
/* Accent */
--accent: 0.967 0.001 286.375;
--accent-foreground: 0.21 0.006 285.885;
/* Destructive - Red */
--destructive: 0.577 0.245 27.325;
/* Border and Input */
--border: 0.92 0.004 286.32;
--input: 0.92 0.004 286.32;
/* Focus ring */
--ring: 0.75 0.183 55.934;
/* Chart colors */
--chart-1: 0.837 0.128 66.29;
--chart-2: 0.705 0.213 47.604;
--chart-3: 0.646 0.222 41.116;
--chart-4: 0.553 0.195 38.402;
--chart-5: 0.47 0.157 37.304;
}
.dark {
/* Dark mode backgrounds */
--background: 0.141 0.005 285.823;
--foreground: 0.985 0 0;
/* Dark mode card */
--card: 0.21 0.006 285.885;
--card-foreground: 0.985 0 0;
/* Dark mode popover */
--popover: 0.21 0.006 285.885;
--popover-foreground: 0.985 0 0;
/* Dark mode primary - Brighter for contrast */
--primary: 0.705 0.213 47.604;
--primary-foreground: 0.98 0.016 73.684;
/* Dark mode secondary */
--secondary: 0.274 0.006 286.033;
--secondary-foreground: 0.985 0 0;
/* Dark mode muted */
--muted: 0.274 0.006 286.033;
--muted-foreground: 0.705 0.015 286.067;
/* Dark mode accent */
--accent: 0.274 0.006 286.033;
--accent-foreground: 0.985 0 0;
/* Dark mode destructive */
--destructive: 0.704 0.191 22.216;
/* Dark mode borders (with alpha) */
--border: 1 0 0 / 10%;
--input: 1 0 0 / 15%;
/* Dark mode focus ring */
--ring: 0.408 0.123 38.172;
/* Chart colors (consistent) */
--chart-1: 0.837 0.128 66.29;
--chart-2: 0.705 0.213 47.604;
--chart-3: 0.646 0.222 41.116;
--chart-4: 0.553 0.195 38.402;
--chart-5: 0.47 0.157 37.304;
}
}
@layer base {
* {
@apply border-border;
}
body {
@apply bg-background text-foreground;
}
}Customizing for Migrated Project:
If migrating an existing app with a design system, extract existing colors and map to CSS variables:
bash
undefined非常重要:所有主题配置必须使用CSS变量
颜色格式:推荐使用OKLCH
本工具使用OKLCH(OKLab Lightness Chroma Hue)颜色空间,而非HSL,以实现更好的感知一致性与颜色准确性。
OKLCH优势:
- 感知均匀(同等数值变化对应同等视觉差异)
- 渐变插值效果更好
- 亮度更可预测
- 无障碍支持更优(对比度计算更准确)
编辑定义设计系统:
app/globals.csscss
@tailwind base;
@tailwind components;
@tailwind utilities;
@layer base {
:root {
--radius: 0.65rem;
/* 背景 - 纯白色 */
--background: 1 0 0;
--foreground: 0.141 0.005 285.823;
/* 卡片 */
--card: 1 0 0;
--card-foreground: 0.141 0.005 285.823;
/* 浮层卡片 */
--popover: 1 0 0;
--popover-foreground: 0.141 0.005 285.823;
/* 主色 - 暖橙色 */
--primary: 0.646 0.222 41.116;
--primary-foreground: 0.98 0.016 73.684;
/* 次要颜色 - 浅紫灰色 */
--secondary: 0.967 0.001 286.375;
--secondary-foreground: 0.21 0.006 285.885;
/* 弱化色 - 次要元素 */
--muted: 0.967 0.001 286.375;
--muted-foreground: 0.552 0.016 285.938;
/* 强调色 */
--accent: 0.967 0.001 286.375;
--accent-foreground: 0.21 0.006 285.885;
/* 危险色 - 红色 */
--destructive: 0.577 0.245 27.325;
/* 边框与输入框 */
--border: 0.92 0.004 286.32;
--input: 0.92 0.004 286.32;
/* 聚焦环 */
--ring: 0.75 0.183 55.934;
/* 图表颜色 */
--chart-1: 0.837 0.128 66.29;
--chart-2: 0.705 0.213 47.604;
--chart-3: 0.646 0.222 41.116;
--chart-4: 0.553 0.195 38.402;
--chart-5: 0.47 0.157 37.304;
}
.dark {
/* 深色模式背景 */
--background: 0.141 0.005 285.823;
--foreground: 0.985 0 0;
/* 深色模式卡片 */
--card: 0.21 0.006 285.885;
--card-foreground: 0.985 0 0;
/* 深色模式浮层卡片 */
--popover: 0.21 0.006 285.885;
--popover-foreground: 0.985 0 0;
/* 深色模式主色 - 更亮以保证对比度 */
--primary: 0.705 0.213 47.604;
--primary-foreground: 0.98 0.016 73.684;
/* 深色模式次要颜色 */
--secondary: 0.274 0.006 286.033;
--secondary-foreground: 0.985 0 0;
/* 深色模式弱化色 */
--muted: 0.274 0.006 286.033;
--muted-foreground: 0.705 0.015 286.067;
/* 深色模式强调色 */
--accent: 0.274 0.006 286.033;
--accent-foreground: 0.985 0 0;
/* 深色模式危险色 */
--destructive: 0.704 0.191 22.216;
/* 深色模式边框(带透明度) */
--border: 1 0 0 / 10%;
--input: 1 0 0 / 15%;
/* 深色模式聚焦环 */
--ring: 0.408 0.123 38.172;
/* 图表颜色(保持一致) */
--chart-1: 0.837 0.128 66.29;
--chart-2: 0.705 0.213 47.604;
--chart-3: 0.646 0.222 41.116;
--chart-4: 0.553 0.195 38.402;
--chart-5: 0.47 0.157 37.304;
}
}
@layer base {
* {
@apply border-border;
}
body {
@apply bg-background text-foreground;
}
}为迁移项目自定义配置:
若迁移的现有项目已有设计系统,提取现有颜色并映射至CSS变量:
bash
undefinedUse the detection script to find existing colors
使用检测脚本查找现有颜色
bash ./scripts/detect-hardcoded-values.sh /path/to/old/codebase
bash ./scripts/detect-hardcoded-values.sh /path/to/old/codebase
Map old colors to new CSS variables (OKLCH format)
将旧颜色映射为新的CSS变量(OKLCH格式)
Use https://oklch.com or https://colorjs.io to convert
Example:
示例:
Old: #FF6B35 (brand orange) → --primary: 0.646 0.222 41.116
旧颜色:#FF6B35(品牌橙)→ --primary: 0.646 0.222 41.116
Old: #3B82F6 (blue) → --primary: 0.630 0.213 255.5
旧颜色:#3B82F6(蓝色)→ --primary: 0.630 0.213 255.5
Old: #10B981 (green) → --success: 0.710 0.180 165.4
旧颜色:#10B981(绿色)→ --success: 0.710 0.180 165.4
undefinedundefined3.5 Install Essential shadcn Components
3.5 安装核心shadcn组件
Use MCP to discover which components you need!
Install core components:
bash
undefined使用MCP查找所需组件!
安装核心组件:
bash
undefinedLayout & Structure
布局与结构
npx shadcn@latest add card
npx shadcn@latest add separator
npx shadcn@latest add card
npx shadcn@latest add separator
Forms
表单
npx shadcn@latest add button
npx shadcn@latest add input
npx shadcn@latest add label
npx shadcn@latest add select
npx shadcn@latest add checkbox
npx shadcn@latest add radio-group
npx shadcn@latest add form
npx shadcn@latest add button
npx shadcn@latest add input
npx shadcn@latest add label
npx shadcn@latest add select
npx shadcn@latest add checkbox
npx shadcn@latest add radio-group
npx shadcn@latest add form
Navigation
导航
npx shadcn@latest add navigation-menu
npx shadcn@latest add tabs
npx shadcn@latest add breadcrumb
npx shadcn@latest add navigation-menu
npx shadcn@latest add tabs
npx shadcn@latest add breadcrumb
Feedback
反馈
npx shadcn@latest add alert
npx shadcn@latest add toast
npx shadcn@latest add dialog
npx shadcn@latest add tooltip
npx shadcn@latest add alert
npx shadcn@latest add toast
npx shadcn@latest add dialog
npx shadcn@latest add tooltip
Data Display
数据展示
npx shadcn@latest add table
npx shadcn@latest add badge
npx shadcn@latest add avatar
npx shadcn@latest add table
npx shadcn@latest add badge
npx shadcn@latest add avatar
Overlays
浮层
npx shadcn@latest add popover
npx shadcn@latest add dropdown-menu
npx shadcn@latest add sheet
**Query MCP for additional components as needed during development.**npx shadcn@latest add popover
npx shadcn@latest add dropdown-menu
npx shadcn@latest add sheet
**开发过程中根据需要,使用MCP查询更多组件。**3.6 Set Up Theme Provider (Dark Mode Support)
3.6 配置主题提供者(深色模式支持)
Install next-themes:
bash
npm install next-themesCreate :
components/theme-provider.tsxtypescript
"use client"
import * as React from "react"
import { ThemeProvider as NextThemesProvider } from "next-themes"
import { type ThemeProviderProps } from "next-themes/dist/types"
export function ThemeProvider({ children, ...props }: ThemeProviderProps) {
return <NextThemesProvider {...props}>{children}</NextThemesProvider>
}Update :
app/layout.tsxtypescript
import { ThemeProvider } from "@/components/theme-provider"
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="en" suppressHydrationWarning>
<body>
<ThemeProvider
attribute="class"
defaultTheme="system"
enableSystem
disableTransitionOnChange
>
{children}
</ThemeProvider>
</body>
</html>
)
}安装next-themes:
bash
npm install next-themes创建:
components/theme-provider.tsxtypescript
"use client"
import * as React from "react"
import { ThemeProvider as NextThemesProvider } from "next-themes"
import { type ThemeProviderProps } from "next-themes/dist/types"
export function ThemeProvider({ children, ...props }: ThemeProviderProps) {
return <NextThemesProvider {...props}>{children}</NextThemesProvider>
}更新:
app/layout.tsxtypescript
import { ThemeProvider } from "@/components/theme-provider"
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="en" suppressHydrationWarning>
<body>
<ThemeProvider
attribute="class"
defaultTheme="system"
enableSystem
disableTransitionOnChange
>
{children}
</ThemeProvider>
</body>
</html>
)
}3.7 Create Example Component
3.7 创建示例组件
Create demonstrating best practices:
components/example-card.tsxtypescript
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
export function ExampleCard() {
return (
<Card className="w-full max-w-md">
<CardHeader>
<CardTitle>shadcn/ui Best Practices</CardTitle>
<CardDescription>
This card demonstrates proper shadcn patterns
</CardDescription>
</CardHeader>
<CardContent>
<p className="text-sm text-muted-foreground">
Notice: No hardcoded colors, using CSS variables via Tailwind classes,
standard shadcn components, and proper typography scale.
</p>
</CardContent>
<CardFooter className="flex justify-between">
<Button variant="outline">Cancel</Button>
<Button>Continue</Button>
</CardFooter>
</Card>
)
}Key Patterns Demonstrated:
- Uses standard shadcn components (Card, Button)
- No hardcoded colors (uses )
text-muted-foreground - CSS variables automatically applied via Tailwind
- Semantic variants (, default)
outline - Proper component composition
创建,展示最佳实践:
components/example-card.tsxtypescript
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
export function ExampleCard() {
return (
<Card className="w-full max-w-md">
<CardHeader>
<CardTitle>shadcn/ui最佳实践</CardTitle>
<CardDescription>
此卡片展示了shadcn的正确使用模式
</CardDescription>
</CardHeader>
<CardContent>
<p className="text-sm text-muted-foreground">
注意:无硬编码颜色,通过Tailwind类使用CSS变量,
采用标准shadcn组件,遵循正确的排版层级。
</p>
</CardContent>
<CardFooter className="flex justify-between">
<Button variant="outline">取消</Button>
<Button>继续</Button>
</CardFooter>
</Card>
)
}展示的核心模式:
- 使用标准shadcn组件(Card、Button)
- 无硬编码颜色(使用)
text-muted-foreground - 通过Tailwind自动应用CSS变量
- 使用语义化变体(outline、默认)
- 组件组合方式正确
Phase 4: Systematic Conversion (Detailed Instructions)
阶段4:系统化转换(详细说明)
4.1 Component Conversion Workflow
4.1 组件转换工作流
For each batch of 5-10 components:
Step 1: Review Components in Batch
Load the component files and understand:
- Current functionality
- Props/API
- Styling approach
- State management
- Event handlers
Step 2: Query MCP for shadcn Equivalents
Before converting, use MCP:
- "What's the shadcn component for [component type]?"
- "Show me shadcn [component] props and examples"
- "How to use shadcn [component] with [feature]?"
Step 3: Convert Component
Follow this pattern:
typescript
// OLD: Custom button with hardcoded styles
const CustomButton = ({ children, onClick, variant = 'primary' }) => {
const styles = {
primary: {
backgroundColor: '#3b82f6', // HARDCODED!
color: '#ffffff',
padding: '8px 16px', // HARDCODED!
borderRadius: '6px'
},
secondary: {
backgroundColor: '#6b7280',
color: '#ffffff',
padding: '8px 16px',
borderRadius: '6px'
}
}
return (
<button style={styles[variant]} onClick={onClick}>
{children}
</button>
)
}
// NEW: shadcn Button with CSS variables
import { Button } from "@/components/ui/button"
const CustomButton = ({ children, onClick, variant = 'default' }) => {
return (
<Button variant={variant} onClick={onClick}>
{children}
</Button>
)
}Conversion Checklist:
- ✅ Replace with shadcn component
- ✅ Remove all hardcoded colors
- ✅ Remove inline styles
- ✅ Use Tailwind classes only
- ✅ Use semantic variants (default, outline, destructive, etc.)
- ✅ Preserve all functionality
- ✅ TypeScript types properly defined
Step 4: Replace Hardcoded Values with CSS Variables
typescript
// OLD: Hardcoded spacing and colors
<div style={{
backgroundColor: '#f3f4f6', // WRONG
padding: '20px', // WRONG
margin: '10px 0' // WRONG
}}>
// NEW: Tailwind classes using CSS variables
<div className="bg-secondary p-5 my-2.5">
// Or for custom spacing:
<div className="bg-secondary" style={{ padding: 'var(--spacing-5)' }}>Step 5: Test Functionality
After converting each component:
bash
undefined针对每批次5-10个组件,执行以下步骤:
步骤1:查看批次中的组件
加载组件文件,理解:
- 当前功能
- 属性/API
- 样式方案
- 状态管理
- 事件处理
步骤2:使用MCP查找对应的shadcn组件
转换前,使用MCP查询:
- "[组件类型]对应的shadcn组件是什么?"
- "展示shadcn [组件]的属性与示例"
- "如何在shadcn [组件]中实现[功能]?"
步骤3:转换组件
遵循以下模式:
typescript
// 旧代码:带硬编码样式的自定义按钮
const CustomButton = ({ children, onClick, variant = 'primary' }) => {
const styles = {
primary: {
backgroundColor: '#3b82f6', // 硬编码!
color: '#ffffff',
padding: '8px 16px', // 硬编码!
borderRadius: '6px'
},
secondary: {
backgroundColor: '#6b7280',
color: '#ffffff',
padding: '8px 16px',
borderRadius: '6px'
}
}
return (
<button style={styles[variant]} onClick={onClick}>
{children}
</button>
)
}
// 新代码:使用CSS变量的shadcn Button
import { Button } from "@/components/ui/button"
const CustomButton = ({ children, onClick, variant = 'default' }) => {
return (
<Button variant={variant} onClick={onClick}>
{children}
</Button>
)
}转换检查清单:
- ✅ 替换为shadcn组件
- ✅ 移除所有硬编码颜色
- ✅ 移除内联样式
- ✅ 仅使用Tailwind类
- ✅ 使用语义化变体(default、outline、destructive等)
- ✅ 保留所有功能
- ✅ 正确定义TypeScript类型
步骤4:用CSS变量替换硬编码值
typescript
// 旧代码:硬编码间距与颜色
<div style={{
backgroundColor: '#f3f4f6', // 错误
padding: '20px', // 错误
margin: '10px 0' // 错误
}}>
// 新代码:使用CSS变量的Tailwind类
<div className="bg-secondary p-5 my-2.5">
// 或自定义间距:
<div className="bg-secondary" style={{ padding: 'var(--spacing-5)' }}>步骤5:测试功能
每个组件转换完成后:
bash
undefinedRun tests
运行测试
npm test
npm test
Visual testing
视觉测试
npm run dev
npm run dev
Manually verify component renders correctly
手动验证组件渲染正常
**Step 6: Verify No Violations**
Run detection script on new components:
```bash
bash ./scripts/detect-hardcoded-values.sh src/components/[batch-name]Should return 0 violations.
Step 7: Mark Batch Complete, Move to Next
Update todo list and migration-plan.md with progress.
**步骤6:验证无违规**
对新组件运行检测脚本:
```bash
bash ./scripts/detect-hardcoded-values.sh src/components/[batch-name]应返回0处违规。
步骤7:标记批次完成,进入下一批次
更新待办列表与,记录进度。
migration-plan.md4.2 Common Component Migrations
4.2 常见组件迁移
Refer to for detailed mappings.
./references/shadcn-component-mapping.mdQuick reference:
| Pattern | Old Approach | shadcn Approach |
|---|---|---|
| Button | Custom styled button | |
| Modal/Dialog | Custom overlay | |
| Form Input | Custom input with validation | |
| Dropdown | Custom select | |
| Table | Custom table | |
| Tooltip | Custom hover component | |
| Toast/Notification | Custom notification | |
| Tabs | Custom tab component | |
| Card | Custom card | |
| Badge | Custom badge/pill | |
详细映射参考。
./references/shadcn-component-mapping.md快速参考:
| 模式 | 旧实现方式 | shadcn实现方式 |
|---|---|---|
| 按钮 | 自定义样式按钮 | |
| 模态框 | 自定义浮层 | |
| 表单输入框 | 带验证的自定义输入框 | |
| 下拉菜单 | 自定义选择器 | |
| 表格 | 自定义表格 | |
| 提示框 | 自定义悬浮组件 | |
| 通知 | 自定义通知组件 | |
| 标签页 | 自定义标签页组件 | |
| 卡片 | 自定义卡片 | |
| 徽章 | 自定义徽章/胶囊 | |
4.3 Handling Complex Components
4.3 处理复杂组件
For components without direct shadcn equivalents:
Option 1: Composition
Build using shadcn primitives:
typescript
// Complex dashboard widget using shadcn primitives
import { Card, CardHeader, CardTitle, CardContent } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Badge } from "@/components/ui/badge"
export function DashboardWidget({ title, data, onRefresh }) {
return (
<Card>
<CardHeader className="flex flex-row items-center justify-between">
<CardTitle>{title}</CardTitle>
<Button variant="outline" size="sm" onClick={onRefresh}>
Refresh
</Button>
</CardHeader>
<CardContent>
{data.map(item => (
<div key={item.id} className="flex items-center justify-between py-2">
<span className="text-sm">{item.label}</span>
<Badge variant={item.status === 'success' ? 'default' : 'destructive'}>
{item.value}
</Badge>
</div>
))}
</CardContent>
</Card>
)
}Option 2: Extend shadcn Components
Create custom components that extend shadcn:
typescript
// Custom component extending shadcn Button
import { Button } from "@/components/ui/button"
import { cn } from "@/lib/utils"
interface IconButtonProps extends React.ComponentProps<typeof Button> {
icon: React.ReactNode
}
export function IconButton({ icon, children, className, ...props }: IconButtonProps) {
return (
<Button className={cn("flex items-center gap-2", className)} {...props}>
{icon}
{children}
</Button>
)
}Option 3: Use shadcn Blocks
Use MCP to discover shadcn blocks (pre-built complex components):
"What blocks are available in shadcn for [use case]?"
Install blocks:
bash
npx shadcn@latest add [block-name]对于没有直接对应shadcn组件的情况:
方案1:组件组合
使用shadcn原语构建:
typescript
// 使用shadcn原语构建的复杂仪表盘组件
import { Card, CardHeader, CardTitle, CardContent } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Badge } from "@/components/ui/badge"
export function DashboardWidget({ title, data, onRefresh }) {
return (
<Card>
<CardHeader className="flex flex-row items-center justify-between">
<CardTitle>{title}</CardTitle>
<Button variant="outline" size="sm" onClick={onRefresh}>
刷新
</Button>
</CardHeader>
<CardContent>
{data.map(item => (
<div key={item.id} className="flex items-center justify-between py-2">
<span className="text-sm">{item.label}</span>
<Badge variant={item.status === 'success' ? 'default' : 'destructive'}>
{item.value}
</Badge>
</div>
))}
</CardContent>
</Card>
)
}方案2:扩展shadcn组件
创建基于shadcn组件的自定义组件:
typescript
// 扩展shadcn Button的自定义组件
import { Button } from "@/components/ui/button"
import { cn } from "@/lib/utils"
interface IconButtonProps extends React.ComponentProps<typeof Button> {
icon: React.ReactNode
}
export function IconButton({ icon, children, className, ...props }: IconButtonProps) {
return (
<Button className={cn("flex items-center gap-2", className)} {...props}>
{icon}
{children}
</Button>
)
}方案3:使用shadcn Blocks
使用MCP查找shadcn Blocks(预构建的复杂组件):
"shadcn针对[使用场景]有哪些Blocks可用?"
安装Blocks:
bash
npx shadcn@latest add [block-name]4.4 Page and Route Conversion
4.4 页面与路由转换
Convert pages to Next.js App Router structure:
Old Structure (React Router):
src/
pages/
Home.tsx
About.tsx
Dashboard.tsx
users/
UserList.tsx
UserDetail.tsxNew Structure (Next.js App Router):
app/
page.tsx # Home
about/
page.tsx # About
dashboard/
page.tsx # Dashboard
layout.tsx # Dashboard layout
users/
page.tsx # UserList
[id]/
page.tsx # UserDetail
layout.tsx # Root layout
loading.tsx # Loading state
error.tsx # Error boundaryExample Conversion:
typescript
// OLD: React Router page
// src/pages/Dashboard.tsx
import { useNavigate } from 'react-router-dom'
export function Dashboard() {
const navigate = useNavigate()
return (
<div style={{ padding: '20px' }}>
<h1>Dashboard</h1>
<button onClick={() => navigate('/users')}>
View Users
</button>
</div>
)
}
// NEW: Next.js App Router page
// app/dashboard/page.tsx
import Link from 'next/link'
import { Button } from '@/components/ui/button'
export default function DashboardPage() {
return (
<div className="container py-6">
<h1 className="text-3xl font-bold mb-6">Dashboard</h1>
<Link href="/users">
<Button>View Users</Button>
</Link>
</div>
)
}Key Changes:
- Default export for pages
- Use Next.js instead of router navigation
<Link> - Remove hardcoded padding → Tailwind classes
- Use shadcn Button
将页面转换为Next.js App Router结构:
旧结构(React Router):
src/
pages/
Home.tsx
About.tsx
Dashboard.tsx
users/
UserList.tsx
UserDetail.tsx新结构(Next.js App Router):
app/
page.tsx // 首页
about/
page.tsx // 关于页
dashboard/
page.tsx // 仪表盘
layout.tsx // 仪表盘布局
users/
page.tsx // 用户列表
[id]/
page.tsx // 用户详情
layout.tsx // 根布局
loading.tsx // 加载状态
error.tsx // 错误边界转换示例:
typescript
// 旧代码:React Router页面
// src/pages/Dashboard.tsx
import { useNavigate } from 'react-router-dom'
export function Dashboard() {
const navigate = useNavigate()
return (
<div style={{ padding: '20px' }}>
<h1>Dashboard</h1>
<button onClick={() => navigate('/users')}>
查看用户
</button>
</div>
)
}
// 新代码:Next.js App Router页面
// app/dashboard/page.tsx
import Link from 'next/link'
import { Button } from '@/components/ui/button'
export default function DashboardPage() {
return (
<div className="container py-6">
<h1 className="text-3xl font-bold mb-6">仪表盘</h1>
<Link href="/users">
<Button>查看用户</Button>
</Link>
</div>
)
}核心变化:
- 页面使用默认导出
- 使用Next.js 替代路由导航
<Link> - 移除硬编码padding → 使用Tailwind类
- 使用shadcn Button
4.5 State Management Migration
4.5 状态管理迁移
Load reference: for state management patterns
./references/react-to-nextjs.mdCommon patterns:
Local State (useState):
- Remains the same in Next.js App Router
- Mark client components with
"use client"
Global State:
- Redux → Zustand or React Context
- MobX → Zustand
- Recoil → Zustand or Jotai
Server State:
- React Query → TanStack Query (still works in Next.js)
- SWR → SWR (Next.js compatible)
- Or use Next.js Server Components for server data
参考中的状态管理模式
./references/react-to-nextjs.md常见模式:
局部状态(useState):
- 在Next.js App Router中保持不变
- 客户端组件需标记
"use client"
全局状态:
- Redux → Zustand或React Context
- MobX → Zustand
- Recoil → Zustand或Jotai
服务端状态:
- React Query → TanStack Query(在Next.js中仍可使用)
- SWR → SWR(兼容Next.js)
- 或使用Next.js服务端组件获取服务端数据
Phase 5: Verification & Cleanup (Detailed Instructions)
阶段5:验证与清理(详细说明)
5.1 Run Test Suite
5.1 运行测试套件
bash
undefinedbash
undefinedRun all tests
运行所有测试
npm test
npm test
Run with coverage
带覆盖率的测试
npm test -- --coverage
npm test -- --coverage
Ensure 100% of migrated components have passing tests
确保所有迁移后的组件测试通过
undefinedundefined5.2 Visual Regression Testing
5.2 视觉回归测试
Manual verification checklist:
- All pages render correctly
- All components match design system
- Dark mode works correctly
- Responsive design maintained
- No hardcoded colors visible
- Consistent spacing throughout
- Typography follows design system
Optional: Set up automated visual regression testing with Percy, Chromatic, or Playwright.
手动验证检查清单:
- 所有页面渲染正常
- 所有组件符合设计系统
- 深色模式正常工作
- 响应式设计保持完好
- 无硬编码颜色显示
- 间距保持一致
- 排版遵循设计系统
可选:使用Percy、Chromatic或Playwright设置自动化视觉回归测试。
5.3 Responsive Design Testing
5.3 响应式设计测试
Critical: Test on real devices, not just browser DevTools
Refer to: for comprehensive responsive testing guidelines.
./references/responsive-design-patterns.mdDevice Testing Checklist:
- iPhone SE (320px - smallest modern viewport)
- iPhone 14 Pro (390px)
- iPad (768px)
- iPad Pro (1024px)
- Desktop (1280px - 1920px)
- Ultrawide (2560px+)
Orientation Testing:
- Portrait mode on mobile/tablet
- Landscape mode on mobile/tablet
- Responsive behavior when rotating device
Responsive Patterns Verification:
- Navigation: Mobile hamburger → tablet sidebar → desktop navbar
- Data tables: Mobile cards → tablet scrollable → desktop full table
- Grids: 1 col mobile → 2 cols tablet → 3-4 cols desktop
- Forms: Single column mobile → multi-column desktop
- Touch targets: Minimum 44x44px on mobile
- Typography: Readable at all screen sizes (minimum 16px body text)
- Images: Responsive sizing with proper aspect ratios
Breakpoint Verification:
bash
undefined关键:在真实设备上测试,而非仅依赖浏览器开发者工具
参考获取全面的响应式测试指南。
./references/responsive-design-patterns.md设备测试检查清单:
- iPhone SE(320px - 最小现代视口)
- iPhone 14 Pro(390px)
- iPad(768px)
- iPad Pro(1024px)
- 桌面端(1280px - 1920px)
- 超宽屏(2560px+)
方向测试:
- 移动端/平板端竖屏模式
- 移动端/平板端横屏模式
- 设备旋转时的响应式表现
响应式模式验证:
- 导航:移动端汉堡菜单 → 平板端侧边栏 → 桌面端导航栏
- 数据表格:移动端卡片 → 平板端可滚动 → 桌面端完整表格
- 网格:移动端1列 → 平板端2列 → 桌面端3-4列
- 表单:移动端单列 → 桌面端多列
- 触摸目标:移动端最小44x44px
- 排版:所有屏幕尺寸下可读(正文最小16px)
- 图片:响应式尺寸,保持正确宽高比
断点验证:
bash
undefinedTest all Tailwind breakpoints
测试所有Tailwind断点
sm: 640px, md: 768px, lg: 1024px, xl: 1280px, 2xl: 1536px
sm: 640px, md: 768px, lg: 1024px, xl: 1280px, 2xl: 1536px
Verify components respond correctly at each breakpoint
验证组件在每个断点下的响应是否正确
**Example Components:**
Review `./assets/component-templates/` for responsive design examples:
- `responsive-navigation.tsx` - Mobile/tablet/desktop navigation patterns
- `responsive-data-table.tsx` - Responsive table with mobile cards
- `responsive-dashboard.tsx` - Responsive grid layouts
- `complex-form.tsx` - Multi-step responsive form
**示例组件:**
查看`./assets/component-templates/`中的响应式设计示例:
- `responsive-navigation.tsx` - 移动端/平板端/桌面端导航模式
- `responsive-data-table.tsx` - 移动端卡片、桌面端表格的响应式表格
- `responsive-dashboard.tsx` - 响应式网格布局仪表盘
- `complex-form.tsx` - 多步骤响应式表单5.4 Run Final Hardcoded Values Check
5.4 最终硬编码值检查
bash
bash ./scripts/detect-hardcoded-values.sh src/Expected result: 0 violations
If violations found, return to Phase 4 and fix.
bash
bash ./scripts/detect-hardcoded-values.sh src/预期结果:0处违规
若发现违规,返回阶段4修复。
5.5 Accessibility Audit (WCAG 2.1 Level AA)
5.5 无障碍审计(WCAG 2.1 Level AA)
Critical: Achieve WCAG 2.1 Level AA compliance
Refer to: for comprehensive accessibility testing guidelines.
./references/accessibility-best-practices.mdbash
undefined关键:达到WCAG 2.1 Level AA合规
参考获取全面的无障碍测试指南。
./references/accessibility-best-practices.mdbash
undefinedInstall axe DevTools or use Lighthouse
安装axe DevTools或使用Lighthouse
npm install -D @axe-core/playwright
npm install -D @axe-core/playwright
Run accessibility tests
运行无障碍测试
npm run test:a11y
shadcn/ui components are built with accessibility in mind (using Radix UI primitives), but verify:
**Automated Testing:**
- [ ] Run axe DevTools browser extension on all pages
- [ ] Lighthouse accessibility score >= 90
- [ ] No WCAG violations reported by automated tools
- [ ] eslint-plugin-jsx-a11y passing (if configured)
**Keyboard Navigation (WCAG 2.1.1, 2.1.2):**
- [ ] All interactive elements accessible via Tab
- [ ] Logical tab order (follows visual layout)
- [ ] No keyboard traps (can Tab out of all components)
- [ ] Enter/Space activates buttons/links
- [ ] Escape closes modals/dialogs
- [ ] Arrow keys navigate within components (tabs, menus, radio groups)
- [ ] Focus indicators visible on all interactive elements
**Screen Reader Testing:**
Test with real screen readers:
- **macOS**: VoiceOver (Cmd + F5)
- **Windows**: NVDA (free) or JAWS
- **Mobile**: VoiceOver (iOS) or TalkBack (Android)
**Screen Reader Checklist (WCAG 1.3.1, 4.1.2):**
- [ ] All images have alt text
- [ ] Form inputs have associated labels
- [ ] Buttons have descriptive text or aria-label
- [ ] Headings follow logical hierarchy (h1 → h2 → h3)
- [ ] Landmarks present (header, nav, main, aside, footer)
- [ ] Dynamic content announces via aria-live regions
- [ ] Error messages announced to screen readers
**Color Contrast (WCAG 1.4.3):**
- [ ] Body text: Minimum 4.5:1 contrast ratio
- [ ] Large text (18pt+): Minimum 3:1 contrast ratio
- [ ] UI components: Minimum 3:1 contrast ratio
- [ ] Focus indicators: Minimum 3:1 contrast ratio
- [ ] Test both light and dark modes
**Forms Accessibility (WCAG 3.3.1, 3.3.2):**
- [ ] All inputs have visible labels
- [ ] Required fields clearly indicated
- [ ] Error messages specific and helpful
- [ ] Error messages associated with inputs (aria-describedby)
- [ ] Form validation doesn't rely on color alone
**Touch Targets (WCAG 2.5.5):**
- [ ] Minimum 44x44 CSS pixels for all touch targets on mobile
- [ ] Adequate spacing between touch targets (8px minimum)
**ARIA Usage (WCAG 4.1.2):**
- [ ] ARIA labels for icon-only buttons
- [ ] aria-expanded for collapsible sections
- [ ] aria-selected for tabs
- [ ] aria-hidden for decorative elements
- [ ] role="alert" for error messages
- [ ] role="status" for non-critical updates
**Complete WCAG 2.1 AA Checklist:**
See `./references/accessibility-best-practices.md` for full WCAG 2.1 Level AA checklist.npm run test:a11y
shadcn/ui组件基于Radix UI原语构建,原生支持无障碍,但仍需验证:
**自动化测试:**
- [ ] 在所有页面运行axe DevTools浏览器扩展
- [ ] Lighthouse无障碍评分≥90
- [ ] 自动化工具未报告WCAG违规
- [ ] eslint-plugin-jsx-a11y检查通过(若已配置)
**键盘导航(WCAG 2.1.1、2.1.2):**
- [ ] 所有交互元素可通过Tab访问
- [ ] 合理的Tab顺序(遵循视觉布局)
- [ ] 无键盘陷阱(可从所有组件Tab跳出)
- [ ] Enter/Space激活按钮/链接
- [ ] Escape关闭模态框/对话框
- [ ] 方向键在组件内导航(标签页、菜单、单选组)
- [ ] 所有交互元素的焦点指示器可见
**屏幕阅读器测试:**
使用真实屏幕阅读器测试:
- **macOS**:VoiceOver(Cmd + F5)
- **Windows**:NVDA(免费)或JAWS
- **移动端**:VoiceOver(iOS)或TalkBack(Android)
**屏幕阅读器检查清单(WCAG 1.3.1、4.1.2):**
- [ ] 所有图片有替代文本
- [ ] 表单输入框关联标签
- [ ] 按钮有描述性文本或aria-label
- [ ] 标题遵循逻辑层级(h1 → h2 → h3)
- [ ] 存在地标元素(header、nav、main、aside、footer)
- [ ] 动态内容通过aria-live区域通知
- [ ] 错误消息可被屏幕阅读器读取
**颜色对比度(WCAG 1.4.3):**
- [ ] 正文文本:最小4.5:1对比度
- [ ] 大文本(18pt+):最小3:1对比度
- [ ] UI组件:最小3:1对比度
- [ ] 焦点指示器:最小3:1对比度
- [ ] 同时测试亮色与暗色模式
**表单无障碍(WCAG 3.3.1、3.3.2):**
- [ ] 所有输入框有可见标签
- [ ] 必填字段清晰标记
- [ ] 错误消息具体且有帮助
- [ ] 错误消息与输入框关联(aria-describedby)
- [ ] 表单验证不单独依赖颜色
**触摸目标(WCAG 2.5.5):**
- [ ] 移动端所有触摸目标最小44x44 CSS像素
- [ ] 触摸目标间有足够间距(最小8px)
**ARIA使用(WCAG 4.1.2):**
- [ ] 仅图标按钮的ARIA标签
- [ ] 可折叠区域的aria-expanded
- [ ] 标签页的aria-selected
- [ ] 装饰元素的aria-hidden
- [ ] 错误消息的role="alert"
- [ ] 非关键更新的role="status"
**完整WCAG 2.1 AA检查清单:**
查看`./references/accessibility-best-practices.md`获取完整的WCAG 2.1 Level AA检查清单。5.6 Performance Audit
5.6 性能审计
bash
undefinedbash
undefinedBuild for production
构建生产版本
npm run build
npm run build
Analyze bundle
分析包大小
npm run analyze # If you have bundle analyzer configured
Run Lighthouse audit:
- Performance >= 90
- Accessibility >= 90
- Best Practices >= 90
- SEO >= 90
**Performance Checklist:**
- [ ] Core Web Vitals meet "Good" thresholds
- LCP (Largest Contentful Paint) < 2.5s
- FID (First Input Delay) < 100ms
- CLS (Cumulative Layout Shift) < 0.1
- [ ] Images optimized (using Next.js Image component)
- [ ] Code splitting implemented for large components
- [ ] Lazy loading below-the-fold content
- [ ] Bundle size reasonable (check with bundle analyzer)npm run analyze # 若已配置包分析工具
运行Lighthouse审计:
- 性能≥90
- 无障碍≥90
- 最佳实践≥90
- SEO≥90
**性能检查清单:**
- [ ] Core Web Vitals达到"良好"阈值
- LCP(最大内容绘制)< 2.5s
- FID(首次输入延迟)< 100ms
- CLS(累积布局偏移)< 0.1
- [ ] 图片已优化(使用Next.js Image组件)
- [ ] 大型组件已实现代码分割
- [ ] 视口外内容懒加载
- [ ] 包大小合理(使用包分析工具检查)5.7 Remove Old Code
5.7 移除旧代码
Once migration is verified:
bash
undefined迁移验证完成后:
bash
undefinedRemove old framework code
移除旧框架代码
rm -rf src/old-components/ # or whatever old structure was
rm -rf src/old-components/ # 或旧代码所在的其他目录
Remove old dependencies
移除旧依赖
npm uninstall [old-framework] [old-ui-library] styled-components emotion ...
npm uninstall [old-framework] [old-ui-library] styled-components emotion ...
Clean up old config files
清理旧配置文件
rm -f .babelrc webpack.config.js # etc.
undefinedrm -f .babelrc webpack.config.js # 等
undefined5.8 Generate Completion Report
5.8 生成完成报告
Create :
migration-complete-report.mdmarkdown
undefined创建:
migration-complete-report.mdmarkdown
undefinedMigration Completion Report
迁移完成报告
Summary
摘要
Successfully migrated [Project Name] from [Old Framework] to Next.js + shadcn/ui.
已成功将[项目名称]从[旧框架]迁移至Next.js + shadcn/ui技术栈。
Statistics
统计数据
- Components Migrated: 47
- Lines of Code Changed: ~5,200
- Hardcoded Values Removed: 231
- CSS Variables Added: 48
- shadcn Components Used: 18
- 已迁移组件数:47个
- 修改代码行数:约5,200行
- 移除硬编码值:231处
- 添加CSS变量:48个
- 使用shadcn组件数:18个
Test Results
测试结果
- Unit Tests: 142/142 passing
- Integration Tests: 23/23 passing
- Accessibility Score: 98/100
- Lighthouse Performance: 94/100
- 单元测试:142/142通过
- 集成测试:23/23通过
- 无障碍评分:98/100
- Lighthouse性能:94/100
Before/After Comparison
前后对比
Before
迁移前
- Framework: React 18 + Vite
- Styling: styled-components + custom CSS
- Hardcoded values: 231 violations
- Bundle size: 523 KB
- Lighthouse: 76
- 框架:React 18 + Vite
- 样式:styled-components + 自定义CSS
- 硬编码值:231处违规
- 包大小:523 KB
- Lighthouse评分:76
After
迁移后
- Framework: Next.js 15 + App Router
- Styling: Tailwind CSS + shadcn/ui
- Hardcoded values: 0 violations
- Bundle size: 398 KB (24% reduction)
- Lighthouse: 94 (23% improvement)
- 框架:Next.js 15 + App Router
- 样式:Tailwind CSS + shadcn/ui
- 硬编码值:0处违规
- 包大小:398 KB(减少24%)
- Lighthouse评分:94(提升23%)
Design System
设计系统
All components now use CSS variables defined in globals.css:
- 24 color tokens
- 12 spacing tokens
- 8 typography tokens
- Full dark mode support
所有组件现在使用中定义的CSS变量:
globals.css- 24个颜色令牌
- 12个间距令牌
- 8个排版令牌
- 完整深色模式支持
Next Steps
下一步计划
- Deploy to production
- Monitor performance metrics
- Gather user feedback
- Optional: Implement additional shadcn blocks
---- 部署至生产环境
- 监控性能指标
- 收集用户反馈
- 可选:引入更多shadcn Blocks
---shadcn Design Principles (CRITICAL)
shadcn设计原则(关键)
Core Principles
核心原则
1. CSS Variables for All Theming
- NEVER hardcode colors, spacing, or typography
- Define all design tokens as CSS variables in
globals.css - Use Tailwind classes that reference these variables
2. Standard Components Only
- Use shadcn/ui components as-is
- Extend via composition, not modification
- If shadcn doesn't have it, build with shadcn primitives
3. Consistent Design Language
- Follow shadcn's design patterns
- Use semantic variants (default, outline, destructive, ghost, link, secondary)
- Maintain consistent spacing scale
- Typography hierarchy from shadcn
4. No Custom UI Components
- Don't create custom buttons, inputs, cards, etc.
- Use shadcn components or build with shadcn primitives
- Exception: Business logic components (not UI primitives)
5. Accessibility First
- shadcn uses Radix UI (accessible by default)
- Don't override accessibility features
- Test with keyboard navigation and screen readers
1. 所有主题配置使用CSS变量
- 绝对禁止硬编码颜色、间距或排版
- 在中定义所有设计令牌为CSS变量
globals.css - 使用引用这些变量的Tailwind类
2. 仅使用标准组件
- 直接使用shadcn/ui组件
- 通过组合扩展,而非修改
- 若shadcn没有对应组件,使用shadcn原语构建
3. 一致的设计语言
- 遵循shadcn的设计模式
- 使用语义化变体(default、outline、destructive、ghost、link、secondary)
- 保持一致的间距比例
- 采用shadcn的排版层级
4. 禁止自定义UI组件
- 不要创建自定义按钮、输入框、卡片等
- 使用shadcn组件或基于shadcn原语构建
- 例外:业务逻辑组件(非UI原语)
5. 无障碍优先
- shadcn使用Radix UI(原生支持无障碍)
- 不要覆盖无障碍特性
- 通过键盘导航与屏幕阅读器测试
Anti-Patterns to Avoid
需避免的反模式
NEVER DO THESE:
❌ Hardcoded Colors
typescript
// WRONG
<div style={{ backgroundColor: '#3b82f6' }}>
// RIGHT
<div className="bg-primary">❌ Hardcoded Spacing
typescript
// WRONG
<div style={{ padding: '20px', margin: '10px' }}>
// RIGHT
<div className="p-5 m-2.5">❌ Custom Styled Components for UI Primitives
typescript
// WRONG
const CustomButton = styled.button`
background: #3b82f6;
padding: 8px 16px;
border-radius: 6px;
`
// RIGHT
import { Button } from '@/components/ui/button'❌ Inline Styles
typescript
// WRONG
<div style={{ color: 'red', fontSize: '14px' }}>
// RIGHT
<div className="text-destructive text-sm">❌ Hardcoded Fonts
typescript
// WRONG
<h1 style={{ fontFamily: 'Montserrat' }}>
// RIGHT
<h1 className="font-sans text-4xl font-bold">❌ Emoji Icons (use Lucide React icons instead)
typescript
// WRONG
<span>❌ Delete</span>
// RIGHT
import { X } from 'lucide-react'
<Button variant="destructive">
<X className="mr-2 h-4 w-4" />
Delete
</Button>❌ Arbitrary CSS Values
typescript
// WRONG
<div className="text-[#ff0000]">
// RIGHT
<div className="text-destructive">绝对禁止以下操作:
❌ 硬编码颜色
typescript
// 错误
<div style={{ backgroundColor: '#3b82f6' }}>
// 正确
<div className="bg-primary">❌ 硬编码间距
typescript
// 错误
<div style={{ padding: '20px', margin: '10px' }}>
// 正确
<div className="p-5 m-2.5">❌ 为UI原语创建自定义样式组件
typescript
// 错误
const CustomButton = styled.button`
background: #3b82f6;
padding: 8px 16px;
border-radius: 6px;
`
// 正确
import { Button } from '@/components/ui/button'❌ 内联样式
typescript
// 错误
<div style={{ color: 'red', fontSize: '14px' }}>
// 正确
<div className="text-destructive text-sm">❌ 硬编码字体
typescript
// 错误
<h1 style={{ fontFamily: 'Montserrat' }}>
// 正确
<h1 className="font-sans text-4xl font-bold">❌ 使用Emoji图标(改用Lucide React图标)
typescript
// 错误
<span>❌ 删除</span>
// 正确
import { X } from 'lucide-react'
<Button variant="destructive">
<X className="mr-2 h-4 w-4" />
删除
</Button>❌ 任意CSS值
typescript
// 错误
<div className="text-[#ff0000]">
// 正确
<div className="text-destructive">Best Practices
最佳实践
✅ Use Semantic Color Names
typescript
// Use semantic CSS variable names
bg-background
text-foreground
bg-primary
text-primary-foreground
bg-secondary
text-muted-foreground
border-border✅ Use Tailwind Spacing Scale
typescript
// Consistent spacing using Tailwind
p-2, p-4, p-6, p-8 // padding
m-2, m-4, m-6, m-8 // margin
gap-2, gap-4 // flex/grid gap✅ Compose Components
typescript
// Build complex UIs by composing shadcn components
import { Card, CardHeader, CardTitle, CardContent } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'✅ Use MCP for Discovery
typescript
// Before building, ask MCP:
// "What shadcn component should I use for [use case]?"
// "Show me examples of shadcn [component]"✅ Extend via Composition
typescript
// Create higher-level components that compose shadcn
export function FeatureCard({ feature }: { feature: Feature }) {
return (
<Card>
<CardHeader>
<CardTitle>{feature.title}</CardTitle>
</CardHeader>
<CardContent>
<p className="text-muted-foreground">{feature.description}</p>
<Button className="mt-4">Learn More</Button>
</CardContent>
</Card>
)
}✅ 使用语义化颜色名称
typescript
// 使用语义化CSS变量名称
bg-background
text-foreground
bg-primary
text-primary-foreground
bg-secondary
text-muted-foreground
border-border✅ 使用Tailwind间距比例
typescript
// 使用一致的Tailwind间距
p-2, p-4, p-6, p-8 // 内边距
m-2, m-4, m-6, m-8 // 外边距
gap-2, gap-4 // flex/grid间距✅ 组件组合
typescript
// 通过组合shadcn组件构建复杂UI
import { Card, CardHeader, CardTitle, CardContent } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'✅ 使用MCP查找组件
typescript
// 开发前,询问MCP:
// "针对[使用场景],我应该使用哪个shadcn组件?"
// "展示shadcn [组件]的示例"✅ 通过组合扩展
typescript
// 创建组合shadcn组件的高阶组件
export function FeatureCard({ feature }: { feature: Feature }) {
return (
<Card>
<CardHeader>
<CardTitle>{feature.title}</CardTitle>
</CardHeader>
<CardContent>
<p className="text-muted-foreground">{feature.description}</p>
<Button className="mt-4">了解更多</Button>
</CardContent>
</Card>
)
}Reference Files
参考文件
Framework-Specific Migration:
- React to Next.js Migration
- Vue to Next.js Migration
- Angular to Next.js Migration
Component & Styling:
- shadcn Component Mapping Reference
- Advanced shadcn Components Guide ⭐ NEW
- Styling Migration Guide
Responsive Design & Accessibility:
- Responsive Design Patterns Guide ⭐ NEW
- Accessibility Best Practices (WCAG 2.1) ⭐ NEW
Example Component Templates:
- Responsive Navigation - Mobile/tablet/desktop navigation patterns ⭐ NEW
- Responsive Data Table - Card view on mobile, table on desktop ⭐ NEW
- Responsive Dashboard - Responsive grid layouts with stats and charts ⭐ NEW
- Complex Multi-Step Form - Form validation, file uploads, conditional fields ⭐ NEW
- Feature Card Example - Basic shadcn component composition
- User Profile Example - Avatar, badges, and layout patterns
Scripts:
- - Automated codebase analysis
./scripts/analyze-codebase.py - - Find anti-patterns
./scripts/detect-hardcoded-values.sh - - Project initialization
./scripts/init-nextjs-shadcn.sh - - Create migration report
./scripts/generate-migration-report.py
Official Documentation:
- shadcn/ui: https://ui.shadcn.com
- Next.js: https://nextjs.org/docs
- Tailwind CSS: https://tailwindcss.com/docs
- Radix UI: https://www.radix-ui.com
- WCAG 2.1 Guidelines: https://www.w3.org/WAI/WCAG21/quickref/
框架专属迁移指南:
- React转Next.js迁移指南
- Vue转Next.js迁移指南
- Angular转Next.js迁移指南
组件与样式:
- shadcn组件映射参考
- 高级shadcn组件指南 ⭐ 新增
- 样式迁移指南
响应式设计与无障碍:
- 响应式设计模式指南 ⭐ 新增
- 无障碍最佳实践(WCAG 2.1) ⭐ 新增
示例组件模板:
- 响应式导航 - 移动端/平板端/桌面端导航模式 ⭐ 新增
- 响应式数据表格 - 移动端卡片、桌面端表格 ⭐ 新增
- 响应式仪表盘 - 响应式网格布局仪表盘 ⭐ 新增
- 复杂多步骤表单 - 表单验证、文件上传、条件字段 ⭐ 新增
- 功能卡片示例 - 基础shadcn组件组合
- 用户资料示例 - 头像、徽章与布局模式
脚本:
- - 自动化代码库分析
./scripts/analyze-codebase.py - - 查找反模式
./scripts/detect-hardcoded-values.sh - - 项目初始化
./scripts/init-nextjs-shadcn.sh - - 生成迁移报告
./scripts/generate-migration-report.py
官方文档:
- shadcn/ui: https://ui.shadcn.com
- Next.js: https://nextjs.org/docs
- Tailwind CSS: https://tailwindcss.com/docs
- Radix UI: https://www.radix-ui.com
- WCAG 2.1指南: https://www.w3.org/WAI/WCAG21/quickref/
Quick Start for New Projects
新项目快速开始
If creating a new Next.js app (not migrating):
-
Initializebash
bash ./scripts/init-nextjs-shadcn.sh my-app -
Check MCP Accessbash
npx shadcn@latest mcp init --client claude -
Install Components
- Use MCP to discover needed components
- Install with
npx shadcn@latest add [component]
-
Build with Best Practices
- Use CSS variables only
- Compose shadcn components
- Follow design principles above
若创建全新Next.js应用(非迁移):
-
初始化项目bash
bash ./scripts/init-nextjs-shadcn.sh my-app -
检查MCP访问bash
npx shadcn@latest mcp init --client claude -
安装组件
- 使用MCP查找所需组件
- 使用安装
npx shadcn@latest add [component]
-
遵循最佳实践开发
- 仅使用CSS变量
- 组合shadcn组件
- 遵循上述设计原则
Summary
总结
This skill enables systematic frontend migration to Next.js + shadcn/ui with strict adherence to design principles:
- Automated analysis of existing codebases
- Systematic batch conversion (5-10 components at a time)
- Zero tolerance for hardcoded values (CSS variables only)
- MCP integration for shadcn component discovery
- Multi-framework support (React, Vue, Angular, vanilla JS)
- Comprehensive verification (tests, accessibility, performance)
Result: Production-grade Next.js applications following shadcn/ui best practices with consistent design systems, full dark mode support, and no anti-patterns.
本工具支持系统化地将前端项目迁移至Next.js + shadcn/ui技术栈,严格遵循设计原则:
- 自动化分析现有代码库
- 系统化批次转换(每批次5-10个组件)
- 零容忍硬编码值(仅使用CSS变量)
- MCP集成支持shadcn组件查找
- 多框架支持(React、Vue、Angular、原生JS)
- 全面验证(测试、无障碍、性能)
结果: 生产级Next.js应用,遵循shadcn/ui最佳实践,具备一致的设计系统、完整深色模式支持,无反模式。