cra-to-next-migration
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseCRA to Next.js Migration Guide
CRA 迁移至 Next.js 指南
Comprehensive migration guide for converting Create React App projects to Next.js, covering routing, data fetching, components, styling, and deployment. Contains 148 rules across 17 categories, prioritized by migration impact. After a successful migration the application should work the same as it did before the migration.
本指南为将Create React App(CRA)项目转换为Next.js的全面迁移手册,涵盖路由、数据获取、组件、样式及部署等内容。包含17个分类下的148条规则,按迁移影响优先级排序。成功迁移后,应用的功能应与迁移前保持一致。
When to Apply
适用场景
Reference these guidelines when:
- Migrating an existing CRA application to Next.js
- Converting React Router routes to file-based routing
- Adopting Server Components in a client-heavy app
- Moving from client-side rendering to SSR/SSG
- Updating environment variables for Next.js
- Optimizing images and fonts with Next.js built-ins
在以下场景中可参考本指南:
- 将现有CRA应用迁移至Next.js
- 将React Router路由转换为基于文件的路由
- 在以客户端为主的应用中采用Server Components
- 从客户端渲染切换至SSR/SSG
- 为Next.js更新环境变量
- 使用Next.js内置功能优化图片与字体
Version Policy
版本政策
Use Next.js 16.x or later. Do NOT use Next.js 14.x or 15.x.
Before starting migration, check the current latest version:
bash
npm info next versionUse the latest version in your package.json with a caret for minor/patch updates. The minimum supported version for this migration guide is .
^16.0.0请使用Next.js 16.x或更高版本。请勿使用Next.js 14.x或15.x。
开始迁移前,请检查当前最新版本:
bash
npm info next version在package.json中使用带脱字符(^)的最新版本,以支持小版本/补丁更新。本迁移指南支持的最低版本为。
^16.0.0Rule Categories by Priority
按优先级划分的规则分类
| Priority | Category | Impact | Prefix | Rules |
|---|---|---|---|---|
| 1 | Project Setup | CRITICAL | | 6 |
| 2 | Dependencies | CRITICAL | | 1 |
| 3 | Routing | CRITICAL | | 17 |
| 4 | Data Fetching | CRITICAL | | 11 |
| 5 | Components | HIGH | | 9 |
| 6 | Environment Variables | HIGH | | 6 |
| 7 | Styling | HIGH | | 12 |
| 8 | Public Assets | MEDIUM | | 5 |
| 9 | Images | MEDIUM | | 8 |
| 10 | Fonts | MEDIUM | | 6 |
| 11 | SEO & Metadata | MEDIUM | | 9 |
| 12 | API Routes | MEDIUM | | 9 |
| 13 | State Management | MEDIUM | | 8 |
| 14 | Integrations | MEDIUM | | 1 |
| 15 | Testing | LOW | | 9 |
| 16 | Build & Deploy | LOW | | 7 |
| 17 | Common Gotchas | HIGH | | 24 |
| 优先级 | 分类 | 影响程度 | 前缀 | 规则数量 |
|---|---|---|---|---|
| 1 | 项目设置 | 关键 | | 6 |
| 2 | 依赖项 | 关键 | | 1 |
| 3 | 路由 | 关键 | | 17 |
| 4 | 数据获取 | 关键 | | 11 |
| 5 | 组件 | 高 | | 9 |
| 6 | 环境变量 | 高 | | 6 |
| 7 | 样式 | 高 | | 12 |
| 8 | 公共资源 | 中 | | 5 |
| 9 | 图片 | 中 | | 8 |
| 10 | 字体 | 中 | | 6 |
| 11 | SEO & 元数据 | 中 | | 9 |
| 12 | API 路由 | 中 | | 9 |
| 13 | 状态管理 | 中 | | 8 |
| 14 | 集成 | 中 | | 1 |
| 15 | 测试 | 低 | | 9 |
| 16 | 构建与部署 | 低 | | 7 |
| 17 | 常见陷阱 | 高 | | 24 |
Quick Reference
快速参考
1. Project Setup (CRITICAL)
1. 项目设置(关键)
- - Convert CRA folder structure to Next.js App Router
setup-initial-structure - - Update dependencies and scripts
setup-package-json - - Create and configure next.config.js
setup-next-config - - Migrate TypeScript configuration
setup-typescript - - Update ESLint for Next.js
setup-eslint - - Update .gitignore for Next.js
setup-gitignore
- - 将CRA目录结构转换为Next.js App Router结构
setup-initial-structure - - 更新依赖项与脚本
setup-package-json - - 创建并配置next.config.js
setup-next-config - - 迁移TypeScript配置
setup-typescript - - 为Next.js更新ESLint配置
setup-eslint - - 为Next.js更新.gitignore
setup-gitignore
2. Dependencies (CRITICAL)
2. 依赖项(关键)
- - Upgrade dependencies for React 19 compatibility
deps-react19-compatibility
- - 升级依赖项以兼容React 19
deps-react19-compatibility
3. Routing (CRITICAL)
3. 路由(关键)
- - Convert components to file-based routes
routing-basic-pages - - Use [param] syntax for dynamic segments
routing-dynamic-routes - - Use [...slug] for catch-all routes
routing-catch-all-routes - - Use [[...slug]] for optional catch-all
routing-optional-catch-all - - Use (group) folders for organization
routing-route-groups - - Use @slot for parallel routes
routing-parallel-routes - - Use (..) for intercepting routes
routing-intercepting-routes - - Replace react-router Link with next/link
routing-link-component - - Replace useNavigate with useRouter
routing-programmatic-navigation - - Replace useParams with Next.js params
routing-use-params - - Replace useSearchParams properly
routing-use-search-params - - Convert nested routes to layouts
routing-nested-layouts - - Add loading.tsx for suspense
routing-loading-states - - Add error.tsx for error handling
routing-error-boundaries - - Add not-found.tsx for 404 pages
routing-not-found - - Handle hash-based routing for client-only apps
routing-hash-based - - Implement protected route patterns
routing-protected-routes
- - 将组件转换为基于文件的路由
routing-basic-pages - - 使用[param]语法处理动态路由段
routing-dynamic-routes - - 使用[...slug]实现全捕获路由
routing-catch-all-routes - - 使用[[...slug]]实现可选全捕获路由
routing-optional-catch-all - - 使用(group)文件夹进行路由分组管理
routing-route-groups - - 使用@slot实现并行路由
routing-parallel-routes - - 使用(..)实现拦截路由
routing-intercepting-routes - - 用next/link替换react-router的Link组件
routing-link-component - - 用useRouter替换useNavigate
routing-programmatic-navigation - - 用Next.js的params替换useParams
routing-use-params - - 正确替换useSearchParams
routing-use-search-params - - 将嵌套路由转换为布局
routing-nested-layouts - - 添加loading.tsx实现Suspense加载状态
routing-loading-states - - 添加error.tsx处理错误边界
routing-error-boundaries - - 添加not-found.tsx实现404页面
routing-not-found - - 为纯客户端应用处理基于哈希的路由
routing-hash-based - - 实现受保护路由模式
routing-protected-routes
4. Data Fetching (CRITICAL)
4. 数据获取(关键)
- - Convert useEffect fetches to Server Components
data-useeffect-to-rsc - - Convert useEffect to getServerSideProps
data-useeffect-to-ssr - - Convert useEffect to getStaticProps
data-useeffect-to-ssg - - Keep client fetches with proper patterns
data-client-fetch - - Use Server Actions for mutations
data-server-actions - - Configure data revalidation strategies
data-revalidation - - Use Suspense for streaming data
data-streaming - - Fetch data in parallel on server
data-parallel-fetching - - Handle sequential data dependencies
data-sequential-fetching - - Configure fetch caching behavior
data-caching - - Initialize client-only libraries in useEffect
data-client-library-init
- - 将useEffect数据获取转换为Server Components模式
data-useeffect-to-rsc - - 将useEffect转换为getServerSideProps
data-useeffect-to-ssr - - 将useEffect转换为getStaticProps
data-useeffect-to-ssg - - 保留客户端数据获取并采用正确模式
data-client-fetch - - 使用Server Actions处理数据变更
data-server-actions - - 配置数据重新验证策略
data-revalidation - - 使用Suspense实现数据流
data-streaming - - 在服务端并行获取数据
data-parallel-fetching - - 处理有依赖关系的顺序数据获取
data-sequential-fetching - - 配置fetch缓存行为
data-caching - - 在useEffect中初始化仅客户端可用的库
data-client-library-init
5. Components (HIGH)
5. 组件(高)
- - Add 'use client' directive for client components
components-use-client - - Understand server components are default
components-server-default - - Place client boundaries strategically
components-boundary-placement - - Use composition to minimize client JS
components-composition - - Interleave server and client components
components-interleaving - - Ensure props are serializable
components-props-serialization - - Pass server components as children
components-children-pattern - - Handle Context providers properly
components-context-providers - - Wrap third-party client components
components-third-party
- - 为客户端组件添加'use client'指令
components-use-client - - 了解Server Components为默认组件类型
components-server-default - - 合理设置客户端组件边界
components-boundary-placement - - 使用组件组合减少客户端JS体积
components-composition - - 交错使用服务端与客户端组件
components-interleaving - - 确保组件props可序列化
components-props-serialization - - 将服务端组件作为子组件传递
components-children-pattern - - 正确处理Context提供者
components-context-providers - - 包装第三方客户端组件
components-third-party
6. Environment Variables (HIGH)
6. 环境变量(高)
- - Change REACTAPP to NEXTPUBLIC
env-prefix-change - - Use non-prefixed vars for server-only
env-server-only - - Use runtime configuration when needed
env-runtime-config - - Understand .env file loading order
env-local-files - - Understand build-time vs runtime env vars
env-build-time - - Validate required environment variables
env-validation
- - 将REACT_APP_前缀改为NEXT_PUBLIC_
env-prefix-change - - 使用无前缀变量作为仅服务端可用变量
env-server-only - - 必要时使用运行时配置
env-runtime-config - - 了解.env文件加载顺序
env-local-files - - 了解构建时与运行时环境变量的区别
env-build-time - - 验证必要的环境变量
env-validation
7. Styling (HIGH)
7. 样式(高)
- - Move global CSS to app/layout.tsx
styling-global-css - - CSS Modules work with minor changes
styling-css-modules - - Configure Sass support
styling-sass - - Configure Tailwind CSS
styling-tailwind - - Handle CSS-in-JS libraries
styling-css-in-js - - Configure styled-components for SSR
styling-styled-components - - Configure Emotion for SSR
styling-emotion - - Import component styles properly
styling-component-styles - - Configure PostCSS
styling-postcss - - Use :global only in CSS Modules
styling-scss-global-syntax - - Control CSS import order in layouts
styling-css-import-order - - Handle dark mode without hydration mismatch
styling-dark-mode-hydration
- - 将全局CSS移至app/layout.tsx
styling-global-css - - CSS Modules仅需少量修改即可使用
styling-css-modules - - 配置Sass支持
styling-sass - - 配置Tailwind CSS
styling-tailwind - - 处理CSS-in-JS库
styling-css-in-js - - 为SSR配置styled-components
styling-styled-components - - 为SSR配置Emotion
styling-emotion - - 正确导入组件样式
styling-component-styles - - 配置PostCSS
styling-postcss - - 仅在CSS Modules中使用:global语法
styling-scss-global-syntax - - 在布局中控制CSS导入顺序
styling-css-import-order - - 处理暗黑模式下的水合不匹配问题
styling-dark-mode-hydration
8. Public Assets (MEDIUM)
8. 公共资源(中)
- - Public folder works the same way
assets-public-folder - - Use static imports for assets
assets-static-imports - - Reference assets without public prefix
assets-absolute-urls - - Place favicon in app directory
assets-favicon - - Configure web app manifest
assets-manifest
- - Public文件夹使用方式保持不变
assets-public-folder - - 使用静态导入资源
assets-static-imports - - 引用资源时无需添加public前缀
assets-absolute-urls - - 将favicon放置在app目录
assets-favicon - - 配置Web应用清单
assets-manifest
9. Images (MEDIUM)
9. 图片(中)
- - Replace img with next/image
images-next-image - - Provide width and height
images-required-dimensions - - Use fill for responsive images
images-fill-prop - - Use priority for LCP images
images-priority - - Configure blur placeholders
images-placeholder - - Configure remote image domains
images-remote-patterns - - Configure custom image loaders
images-loader - - Understand automatic optimization
images-optimization
- - 用next/image替换img标签
images-next-image - - 提供图片宽度与高度
images-required-dimensions - - 使用fill属性实现响应式图片
images-fill-prop - - 为LCP图片设置priority属性
images-priority - - 配置模糊占位符
images-placeholder - - 配置远程图片域名
images-remote-patterns - - 配置自定义图片加载器
images-loader - - 了解自动优化机制
images-optimization
10. Fonts (MEDIUM)
10. 字体(中)
- - Use next/font for optimization
fonts-next-font - - Load Google Fonts properly
fonts-google-fonts - - Load local font files
fonts-local-fonts - - Configure variable fonts
fonts-variable-fonts - - Configure font-display strategy
fonts-font-display - - Understand automatic font preloading
fonts-preload
- - 使用next/font进行字体优化
fonts-next-font - - 正确加载Google Fonts
fonts-google-fonts - - 加载本地字体文件
fonts-local-fonts - - 配置可变字体
fonts-variable-fonts - - 配置font-display策略
fonts-font-display - - 了解自动字体预加载机制
fonts-preload
11. SEO & Metadata (MEDIUM)
11. SEO & 元数据(中)
- - Use Metadata API instead of react-helmet
seo-metadata-api - - Generate dynamic metadata
seo-dynamic-metadata - - Configure Open Graph metadata
seo-opengraph - - Configure Twitter Card metadata
seo-twitter-cards - - Add structured data (JSON-LD)
seo-json-ld - - Set canonical URLs
seo-canonical - - Configure robots meta tags
seo-robots - - Generate sitemap.xml
seo-sitemap - - Migrate from next/head to Metadata
seo-head-component
- - 使用Metadata API替代react-helmet
seo-metadata-api - - 生成动态元数据
seo-dynamic-metadata - - 配置Open Graph元数据
seo-opengraph - - 配置Twitter Card元数据
seo-twitter-cards - - 添加结构化数据(JSON-LD)
seo-json-ld - - 设置规范URL
seo-canonical - - 配置robots元标签
seo-robots - - 生成sitemap.xml
seo-sitemap - - 从next/head迁移至Metadata API
seo-head-component
12. API Routes (MEDIUM)
12. API 路由(中)
- - Create Route Handlers in app/api
api-route-handlers - - Export named functions for HTTP methods
api-http-methods - - Parse request body properly
api-request-body - - Access query parameters
api-query-params - - Access headers and cookies
api-headers-cookies - - Return proper response types
api-response-types - - Implement middleware patterns
api-middleware - - Configure CORS properly
api-cors - - Implement rate limiting
api-rate-limiting
- - 在app/api中创建路由处理器
api-route-handlers - - 导出命名函数处理HTTP方法
api-http-methods - - 正确解析请求体
api-request-body - - 访问查询参数
api-query-params - - 访问请求头与Cookie
api-headers-cookies - - 返回正确的响应类型
api-response-types - - 实现中间件模式
api-middleware - - 正确配置CORS
api-cors - - 实现请求限流
api-rate-limiting
13. State Management (MEDIUM)
13. 状态管理(中)
- - Context requires 'use client'
state-context-client - - Zustand works with hydration care
state-zustand - - Configure Redux with Next.js
state-redux - - Configure Jotai properly
state-jotai - - Configure Recoil properly
state-recoil - - Use URL for shareable state
state-url-state - - Minimize client state with RSC
state-server-state - - Handle state persistence
state-persistence
- - Context需搭配'use client'使用
state-context-client - - 使用Zustand时注意水合问题
state-zustand - - 为Next.js配置Redux
state-redux - - 正确配置Jotai
state-jotai - - 正确配置Recoil
state-recoil - - 使用URL存储可共享状态
state-url-state - - 利用RSC减少客户端状态
state-server-state - - 处理状态持久化
state-persistence
14. Integrations (MEDIUM)
14. 集成(中)
- - Migrate Sentry error monitoring
integrations-sentry
- - 迁移Sentry错误监控
integrations-sentry
15. Testing (LOW)
15. 测试(低)
- - Update Jest configuration
testing-jest-config - - RTL works the same
testing-react-testing-library - - Test Server Components
testing-server-components - - Test Client Components
testing-client-components - - Test async components
testing-async-components - - Mock Next.js modules
testing-mocking - - Configure Cypress for Next.js
testing-e2e-cypress - - Configure Playwright for Next.js
testing-e2e-playwright - - Test API Route Handlers
testing-api-routes
- - 更新Jest配置
testing-jest-config - - RTL使用方式保持不变
testing-react-testing-library - - 测试Server Components
testing-server-components - - 测试客户端组件
testing-client-components - - 测试异步组件
testing-async-components - - 模拟Next.js模块
testing-mocking - - 为Next.js配置Cypress
testing-e2e-cypress - - 为Next.js配置Playwright
testing-e2e-playwright - - 测试API路由处理器
testing-api-routes
16. Build & Deployment (LOW)
16. 构建与部署(低)
- - Update build scripts
build-scripts - - Understand build output
build-output - - Configure standalone output
build-standalone - - Configure static export
build-static-export - - Analyze bundle size
build-bundle-analysis - - Deploy to Vercel
build-vercel - - Configure Docker deployment
build-docker
- - 更新构建脚本
build-scripts - - 了解构建输出内容
build-output - - 配置独立构建输出
build-standalone - - 配置静态导出
build-static-export - - 分析包体积
build-bundle-analysis - - 部署至Vercel
build-vercel - - 配置Docker部署
build-docker
17. Common Gotchas (HIGH)
17. 常见陷阱(高)
- - Handle window/document in SSR
gotchas-window-undefined - - Fix hydration mismatches
gotchas-hydration-mismatch - - Understand useEffect in Next.js
gotchas-use-effect-timing - - Check router.isReady for query params
gotchas-router-ready - - Use next/dynamic properly
gotchas-dynamic-imports - - Edge vs Node.js runtime
gotchas-api-routes-edge - - Middleware runs on edge
gotchas-middleware - - Static vs dynamic rendering
gotchas-static-generation - - Handle redirects properly
gotchas-redirect - - Set response headers
gotchas-headers - - Handle cookies in RSC
gotchas-cookies - - Handle Turbopack compatibility issues
gotchas-turbopack - - Fix empty module exports for isolatedModules
gotchas-empty-modules - - Fix nullish coalescing runtime errors
gotchas-nullish-coalescing - - Fix React 19 class component this binding
gotchas-react19-class-components - - Handle React 19 ref prop changes
gotchas-react19-ref-prop - - Handle WebSocket native dependency bundling
gotchas-websocket-optional-deps - - Guard against auth/API race conditions
gotchas-auth-race-conditions - - Wait for auth state before checking roles
gotchas-auth-state-gating - - Ensure configuration idempotency with useRef
gotchas-configuration-idempotency - - Avoid nested interactive elements
gotchas-hydration-nested-interactive - - Never call router.push during render
gotchas-router-push-timing - - Prevent infinite re-render loops
gotchas-infinite-rerender - - Configure provider hierarchy correctly
gotchas-provider-hierarchy
- - 在SSR中处理window/document对象
gotchas-window-undefined - - 修复水合不匹配问题
gotchas-hydration-mismatch - - 了解Next.js中useEffect的执行时机
gotchas-use-effect-timing - - 检查router.isReady以获取查询参数
gotchas-router-ready - - 正确使用next/dynamic
gotchas-dynamic-imports - - 区分Edge与Node.js运行时
gotchas-api-routes-edge - - 中间件运行在Edge环境
gotchas-middleware - - 区分静态与动态渲染
gotchas-static-generation - - 正确处理重定向
gotchas-redirect - - 设置响应头
gotchas-headers - - 在RSC中处理Cookie
gotchas-cookies - - 处理Turbopack兼容性问题
gotchas-turbopack - - 修复isolatedModules模式下的空模块导出问题
gotchas-empty-modules - - 修复空值合并运算符的运行时错误
gotchas-nullish-coalescing - - 修复React 19类组件的this绑定问题
gotchas-react19-class-components - - 处理React 19中ref属性的变更
gotchas-react19-ref-prop - - 处理WebSocket原生依赖打包问题
gotchas-websocket-optional-deps - - 防范认证/API竞态条件
gotchas-auth-race-conditions - - 等待认证状态就绪后再检查角色
gotchas-auth-state-gating - - 使用useRef确保配置幂等性
gotchas-configuration-idempotency - - 避免嵌套交互式元素
gotchas-hydration-nested-interactive - - 切勿在渲染期间调用router.push
gotchas-router-push-timing - - 防止无限重渲染循环
gotchas-infinite-rerender - - 正确配置提供者层级
gotchas-provider-hierarchy
Pre-Migration Checklist
迁移前检查清单
Before starting migration, scan the codebase for patterns that need special handling:
bash
undefined开始迁移前,请扫描代码库以识别需要特殊处理的模式:
bash
undefinedCheck for WebSocket libraries (needs webpack fallback config)
检查WebSocket库(需配置webpack fallback)
grep -E "(socket.io|"ws")" package.json
grep -E "(socket.io|"ws")" package.json
Check for SCSS :export syntax (may need --webpack flag)
检查SCSS :export语法(可能需要--webpack标志)
grep -r ":export" --include="*.scss" src/
grep -r ":export" --include="*.scss" src/
Check for SVG ReactComponent imports (needs SVGR config)
检查SVG ReactComponent导入(需配置SVGR)
grep -r "ReactComponent" --include=".ts" --include=".tsx" src/
grep -r "ReactComponent" --include=".ts" --include=".tsx" src/
List all REACT_APP_ environment variables
列出所有REACT_APP_开头的环境变量
grep -roh "REACT_APP_[A-Z_]" --include=".ts" --include=".tsx" --include=".js" --include="*.jsx" src/ | sort -u
grep -roh "REACT_APP_[A-Z_]" --include=".ts" --include=".tsx" --include=".js" --include="*.jsx" src/ | sort -u
Check for Redux extraReducers using object notation (must convert to builder pattern for RTK v2)
检查Redux extraReducers的对象写法(RTK v2需转换为构建器模式)
grep -r "extraReducers:" --include=".js" --include=".jsx" --include=".ts" --include=".tsx" src/
grep -r "extraReducers:" --include=".js" --include=".jsx" --include=".ts" --include=".tsx" src/
Check for /app/ paths that need updating if using (app) route group
检查使用(app)路由组时需要更新的/app/路径
grep -rE "(href|to|push|replace|redirect).['"]/app/" --include=".js" --include=".jsx" --include=".ts" --include="*.tsx" src/
**Scan Results to Rule Mapping:**
| Scan Result | Rules to Read |
| ------------------------------- | ------------------------------------------------------ |
| socket.io or ws in package.json | `gotchas-websocket-optional-deps`, `setup-next-config` |
| `:export` in SCSS files | `gotchas-turbopack` |
| `ReactComponent` SVG imports | `assets-static-imports` |
| `REACT_APP_` variables found | `env-prefix-change` |
| `extraReducers:` found | `state-redux` (RTK v2 builder callback required) |
| `/app/` paths in navigation | `routing-route-groups` (update paths for route groups) |grep -rE "(href|to|push|replace|redirect).['"]/app/" --include=".js" --include=".jsx" --include=".ts" --include="*.tsx" src/
**扫描结果与规则映射:**
| 扫描结果 | 需参考的规则 |
| ------------------------------- | ------------------------------------------------------ |
| package.json中存在socket.io或ws | `gotchas-websocket-optional-deps`, `setup-next-config` |
| SCSS文件中存在`:export` | `gotchas-turbopack` |
| SVG使用ReactComponent导入 | `assets-static-imports` |
| 发现`REACT_APP_`开头的变量 | `env-prefix-change` |
| 发现`extraReducers:`写法 | `state-redux`(RTK v2需使用构建器回调) |
| 导航中存在`/app/`路径 | `routing-route-groups`(更新路由组对应的路径) |How to Use
使用方法
Read individual rule files for detailed explanations and code examples:
rules/setup-initial-structure.md
rules/routing-basic-pages.md
rules/data-useeffect-to-rsc.mdEach rule file contains:
- Brief explanation of the migration step
- CRA "before" code example
- Next.js "after" code example
- Additional context and gotchas
阅读单个规则文件以获取详细说明与代码示例:
rules/setup-initial-structure.md
rules/routing-basic-pages.md
rules/data-useeffect-to-rsc.md每个规则文件包含:
- 迁移步骤的简要说明
- CRA环境下的「迁移前」代码示例
- Next.js环境下的「迁移后」代码示例
- 额外说明与注意事项
Migration Order
迁移顺序
For best results, migrate in this order:
- Setup - Initialize Next.js project structure
- Routing - Convert React Router to file-based routing
- Environment Variables - Update env var prefixes
- Components - Add 'use client' directives where needed
- Data Fetching - Convert useEffect to server patterns
- Styling - Move global CSS, configure CSS-in-JS
- Images & Fonts - Adopt Next.js optimizations
- SEO - Migrate to Metadata API
- API Routes - Create Route Handlers
- Testing - Update test configuration
为获得最佳效果,请按以下顺序进行迁移:
- 项目设置 - 初始化Next.js项目结构
- 路由 - 将React Router转换为基于文件的路由
- 环境变量 - 更新环境变量前缀
- 组件 - 在需要的地方添加'use client'指令
- 数据获取 - 将useEffect转换为服务端模式
- 样式 - 迁移全局CSS,配置CSS-in-JS
- 图片与字体 - 采用Next.js优化方案
- SEO - 迁移至Metadata API
- API路由 - 创建路由处理器
- 测试 - 更新测试配置
Post-Migration Verification Checklist
迁移后验证清单
After migration, verify the application works correctly:
Core Functionality:
- starts Next.js dev server without errors
npm run dev - completes successfully
npm run build - runs the production build
npm start - Main application renders correctly
- All routes are accessible
Client-Side Features:
- localStorage/sessionStorage persistence works
- Dark mode or theme toggles work and persist
- Client-side interactivity (forms, buttons, modals) works
- Browser back/forward navigation works correctly
Routing (if applicable):
- Hash-based routing works (e.g., )
#room=abc,key=xyz - Query parameters are read correctly
- Dynamic routes render with correct params
- 404 pages show for invalid routes
Real-Time Features (if applicable):
- WebSocket connections establish successfully
- Real-time collaboration or updates work
- Reconnection after disconnect works
Integrations (if applicable):
- Error monitoring (Sentry) captures errors
- Analytics tracking fires correctly
- Third-party auth (OAuth, Firebase) works
- File uploads work
PWA (if applicable):
- Service worker registers (production build)
- App is installable
- Offline functionality works as expected
Performance:
- No hydration mismatch warnings in console
- Images load and are optimized
- Fonts load without FOUT/FOIT issues
- No unexpected console errors or warnings
迁移完成后,请验证应用功能是否正常:
核心功能:
- 可正常启动Next.js开发服务器,无错误
npm run dev - 可成功完成
npm run build - 可正常运行生产构建版本
npm start - 主应用可正常渲染
- 所有路由均可访问
客户端功能:
- localStorage/sessionStorage持久化功能正常
- 暗黑模式或主题切换功能正常且可持久化
- 客户端交互功能(表单、按钮、模态框)正常
- 浏览器前进/后退导航功能正常
路由(如适用):
- 基于哈希的路由正常工作(例如:)
#room=abc,key=xyz - 查询参数可正确读取
- 动态路由可根据参数正确渲染
- 无效路由可显示404页面
实时功能(如适用):
- WebSocket连接可成功建立
- 实时协作或更新功能正常
- 断开后重连功能正常
集成功能(如适用):
- 错误监控(Sentry)可捕获错误
- 分析追踪可正常触发
- 第三方认证(OAuth、Firebase)功能正常
- 文件上传功能正常
PWA功能(如适用):
- 生产构建版本中Service Worker可正常注册
- 应用可被安装
- 离线功能符合预期
性能:
- 控制台无水合不匹配警告
- 图片可正常加载并已优化
- 字体加载无FOUT/FOIT问题
- 无意外的控制台错误或警告