cra-to-next-migration

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

CRA 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 version
Use 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.0

Rule Categories by Priority

按优先级划分的规则分类

PriorityCategoryImpactPrefixRules
1Project SetupCRITICAL
setup-
6
2DependenciesCRITICAL
deps-
1
3RoutingCRITICAL
routing-
17
4Data FetchingCRITICAL
data-
11
5ComponentsHIGH
components-
9
6Environment VariablesHIGH
env-
6
7StylingHIGH
styling-
12
8Public AssetsMEDIUM
assets-
5
9ImagesMEDIUM
images-
8
10FontsMEDIUM
fonts-
6
11SEO & MetadataMEDIUM
seo-
9
12API RoutesMEDIUM
api-
9
13State ManagementMEDIUM
state-
8
14IntegrationsMEDIUM
integrations-
1
15TestingLOW
testing-
9
16Build & DeployLOW
build-
7
17Common GotchasHIGH
gotchas-
24
优先级分类影响程度前缀规则数量
1项目设置关键
setup-
6
2依赖项关键
deps-
1
3路由关键
routing-
17
4数据获取关键
data-
11
5组件
components-
9
6环境变量
env-
6
7样式
styling-
12
8公共资源
assets-
5
9图片
images-
8
10字体
fonts-
6
11SEO & 元数据
seo-
9
12API 路由
api-
9
13状态管理
state-
8
14集成
integrations-
1
15测试
testing-
9
16构建与部署
build-
7
17常见陷阱
gotchas-
24

Quick Reference

快速参考

1. Project Setup (CRITICAL)

1. 项目设置(关键)

  • setup-initial-structure
    - Convert CRA folder structure to Next.js App Router
  • setup-package-json
    - Update dependencies and scripts
  • setup-next-config
    - Create and configure next.config.js
  • setup-typescript
    - Migrate TypeScript configuration
  • setup-eslint
    - Update ESLint for Next.js
  • setup-gitignore
    - Update .gitignore for Next.js
  • setup-initial-structure
    - 将CRA目录结构转换为Next.js App Router结构
  • setup-package-json
    - 更新依赖项与脚本
  • setup-next-config
    - 创建并配置next.config.js
  • setup-typescript
    - 迁移TypeScript配置
  • setup-eslint
    - 为Next.js更新ESLint配置
  • setup-gitignore
    - 为Next.js更新.gitignore

2. Dependencies (CRITICAL)

2. 依赖项(关键)

  • deps-react19-compatibility
    - Upgrade dependencies for React 19 compatibility
  • deps-react19-compatibility
    - 升级依赖项以兼容React 19

3. Routing (CRITICAL)

3. 路由(关键)

  • routing-basic-pages
    - Convert components to file-based routes
  • routing-dynamic-routes
    - Use [param] syntax for dynamic segments
  • routing-catch-all-routes
    - Use [...slug] for catch-all routes
  • routing-optional-catch-all
    - Use [[...slug]] for optional catch-all
  • routing-route-groups
    - Use (group) folders for organization
  • routing-parallel-routes
    - Use @slot for parallel routes
  • routing-intercepting-routes
    - Use (..) for intercepting routes
  • routing-link-component
    - Replace react-router Link with next/link
  • routing-programmatic-navigation
    - Replace useNavigate with useRouter
  • routing-use-params
    - Replace useParams with Next.js params
  • routing-use-search-params
    - Replace useSearchParams properly
  • routing-nested-layouts
    - Convert nested routes to layouts
  • routing-loading-states
    - Add loading.tsx for suspense
  • routing-error-boundaries
    - Add error.tsx for error handling
  • routing-not-found
    - Add not-found.tsx for 404 pages
  • routing-hash-based
    - Handle hash-based routing for client-only apps
  • routing-protected-routes
    - Implement protected route patterns
  • routing-basic-pages
    - 将组件转换为基于文件的路由
  • routing-dynamic-routes
    - 使用[param]语法处理动态路由段
  • routing-catch-all-routes
    - 使用[...slug]实现全捕获路由
  • routing-optional-catch-all
    - 使用[[...slug]]实现可选全捕获路由
  • routing-route-groups
    - 使用(group)文件夹进行路由分组管理
  • routing-parallel-routes
    - 使用@slot实现并行路由
  • routing-intercepting-routes
    - 使用(..)实现拦截路由
  • routing-link-component
    - 用next/link替换react-router的Link组件
  • routing-programmatic-navigation
    - 用useRouter替换useNavigate
  • routing-use-params
    - 用Next.js的params替换useParams
  • routing-use-search-params
    - 正确替换useSearchParams
  • routing-nested-layouts
    - 将嵌套路由转换为布局
  • routing-loading-states
    - 添加loading.tsx实现Suspense加载状态
  • routing-error-boundaries
    - 添加error.tsx处理错误边界
  • routing-not-found
    - 添加not-found.tsx实现404页面
  • routing-hash-based
    - 为纯客户端应用处理基于哈希的路由
  • routing-protected-routes
    - 实现受保护路由模式

4. Data Fetching (CRITICAL)

4. 数据获取(关键)

  • data-useeffect-to-rsc
    - Convert useEffect fetches to Server Components
  • data-useeffect-to-ssr
    - Convert useEffect to getServerSideProps
  • data-useeffect-to-ssg
    - Convert useEffect to getStaticProps
  • data-client-fetch
    - Keep client fetches with proper patterns
  • data-server-actions
    - Use Server Actions for mutations
  • data-revalidation
    - Configure data revalidation strategies
  • data-streaming
    - Use Suspense for streaming data
  • data-parallel-fetching
    - Fetch data in parallel on server
  • data-sequential-fetching
    - Handle sequential data dependencies
  • data-caching
    - Configure fetch caching behavior
  • data-client-library-init
    - Initialize client-only libraries in useEffect
  • data-useeffect-to-rsc
    - 将useEffect数据获取转换为Server Components模式
  • data-useeffect-to-ssr
    - 将useEffect转换为getServerSideProps
  • data-useeffect-to-ssg
    - 将useEffect转换为getStaticProps
  • data-client-fetch
    - 保留客户端数据获取并采用正确模式
  • data-server-actions
    - 使用Server Actions处理数据变更
  • data-revalidation
    - 配置数据重新验证策略
  • data-streaming
    - 使用Suspense实现数据流
  • data-parallel-fetching
    - 在服务端并行获取数据
  • data-sequential-fetching
    - 处理有依赖关系的顺序数据获取
  • data-caching
    - 配置fetch缓存行为
  • data-client-library-init
    - 在useEffect中初始化仅客户端可用的库

5. Components (HIGH)

5. 组件(高)

  • components-use-client
    - Add 'use client' directive for client components
  • components-server-default
    - Understand server components are default
  • components-boundary-placement
    - Place client boundaries strategically
  • components-composition
    - Use composition to minimize client JS
  • components-interleaving
    - Interleave server and client components
  • components-props-serialization
    - Ensure props are serializable
  • components-children-pattern
    - Pass server components as children
  • components-context-providers
    - Handle Context providers properly
  • components-third-party
    - Wrap third-party client components
  • components-use-client
    - 为客户端组件添加'use client'指令
  • components-server-default
    - 了解Server Components为默认组件类型
  • components-boundary-placement
    - 合理设置客户端组件边界
  • components-composition
    - 使用组件组合减少客户端JS体积
  • components-interleaving
    - 交错使用服务端与客户端组件
  • components-props-serialization
    - 确保组件props可序列化
  • components-children-pattern
    - 将服务端组件作为子组件传递
  • components-context-providers
    - 正确处理Context提供者
  • components-third-party
    - 包装第三方客户端组件

6. Environment Variables (HIGH)

6. 环境变量(高)

  • env-prefix-change
    - Change REACTAPP to NEXTPUBLIC
  • env-server-only
    - Use non-prefixed vars for server-only
  • env-runtime-config
    - Use runtime configuration when needed
  • env-local-files
    - Understand .env file loading order
  • env-build-time
    - Understand build-time vs runtime env vars
  • env-validation
    - Validate required environment variables
  • env-prefix-change
    - 将REACT_APP_前缀改为NEXT_PUBLIC_
  • env-server-only
    - 使用无前缀变量作为仅服务端可用变量
  • env-runtime-config
    - 必要时使用运行时配置
  • env-local-files
    - 了解.env文件加载顺序
  • env-build-time
    - 了解构建时与运行时环境变量的区别
  • env-validation
    - 验证必要的环境变量

7. Styling (HIGH)

7. 样式(高)

  • styling-global-css
    - Move global CSS to app/layout.tsx
  • styling-css-modules
    - CSS Modules work with minor changes
  • styling-sass
    - Configure Sass support
  • styling-tailwind
    - Configure Tailwind CSS
  • styling-css-in-js
    - Handle CSS-in-JS libraries
  • styling-styled-components
    - Configure styled-components for SSR
  • styling-emotion
    - Configure Emotion for SSR
  • styling-component-styles
    - Import component styles properly
  • styling-postcss
    - Configure PostCSS
  • styling-scss-global-syntax
    - Use :global only in CSS Modules
  • styling-css-import-order
    - Control CSS import order in layouts
  • styling-dark-mode-hydration
    - Handle dark mode without hydration mismatch
  • styling-global-css
    - 将全局CSS移至app/layout.tsx
  • styling-css-modules
    - CSS Modules仅需少量修改即可使用
  • styling-sass
    - 配置Sass支持
  • styling-tailwind
    - 配置Tailwind CSS
  • styling-css-in-js
    - 处理CSS-in-JS库
  • styling-styled-components
    - 为SSR配置styled-components
  • styling-emotion
    - 为SSR配置Emotion
  • styling-component-styles
    - 正确导入组件样式
  • styling-postcss
    - 配置PostCSS
  • styling-scss-global-syntax
    - 仅在CSS Modules中使用:global语法
  • styling-css-import-order
    - 在布局中控制CSS导入顺序
  • styling-dark-mode-hydration
    - 处理暗黑模式下的水合不匹配问题

8. Public Assets (MEDIUM)

8. 公共资源(中)

  • assets-public-folder
    - Public folder works the same way
  • assets-static-imports
    - Use static imports for assets
  • assets-absolute-urls
    - Reference assets without public prefix
  • assets-favicon
    - Place favicon in app directory
  • assets-manifest
    - Configure web app manifest
  • assets-public-folder
    - Public文件夹使用方式保持不变
  • assets-static-imports
    - 使用静态导入资源
  • assets-absolute-urls
    - 引用资源时无需添加public前缀
  • assets-favicon
    - 将favicon放置在app目录
  • assets-manifest
    - 配置Web应用清单

9. Images (MEDIUM)

9. 图片(中)

  • images-next-image
    - Replace img with next/image
  • images-required-dimensions
    - Provide width and height
  • images-fill-prop
    - Use fill for responsive images
  • images-priority
    - Use priority for LCP images
  • images-placeholder
    - Configure blur placeholders
  • images-remote-patterns
    - Configure remote image domains
  • images-loader
    - Configure custom image loaders
  • images-optimization
    - Understand automatic optimization
  • images-next-image
    - 用next/image替换img标签
  • images-required-dimensions
    - 提供图片宽度与高度
  • images-fill-prop
    - 使用fill属性实现响应式图片
  • images-priority
    - 为LCP图片设置priority属性
  • images-placeholder
    - 配置模糊占位符
  • images-remote-patterns
    - 配置远程图片域名
  • images-loader
    - 配置自定义图片加载器
  • images-optimization
    - 了解自动优化机制

10. Fonts (MEDIUM)

10. 字体(中)

  • fonts-next-font
    - Use next/font for optimization
  • fonts-google-fonts
    - Load Google Fonts properly
  • fonts-local-fonts
    - Load local font files
  • fonts-variable-fonts
    - Configure variable fonts
  • fonts-font-display
    - Configure font-display strategy
  • fonts-preload
    - Understand automatic font preloading
  • fonts-next-font
    - 使用next/font进行字体优化
  • fonts-google-fonts
    - 正确加载Google Fonts
  • fonts-local-fonts
    - 加载本地字体文件
  • fonts-variable-fonts
    - 配置可变字体
  • fonts-font-display
    - 配置font-display策略
  • fonts-preload
    - 了解自动字体预加载机制

11. SEO & Metadata (MEDIUM)

11. SEO & 元数据(中)

  • seo-metadata-api
    - Use Metadata API instead of react-helmet
  • seo-dynamic-metadata
    - Generate dynamic metadata
  • seo-opengraph
    - Configure Open Graph metadata
  • seo-twitter-cards
    - Configure Twitter Card metadata
  • seo-json-ld
    - Add structured data (JSON-LD)
  • seo-canonical
    - Set canonical URLs
  • seo-robots
    - Configure robots meta tags
  • seo-sitemap
    - Generate sitemap.xml
  • seo-head-component
    - Migrate from next/head to Metadata
  • seo-metadata-api
    - 使用Metadata API替代react-helmet
  • seo-dynamic-metadata
    - 生成动态元数据
  • seo-opengraph
    - 配置Open Graph元数据
  • seo-twitter-cards
    - 配置Twitter Card元数据
  • seo-json-ld
    - 添加结构化数据(JSON-LD)
  • seo-canonical
    - 设置规范URL
  • seo-robots
    - 配置robots元标签
  • seo-sitemap
    - 生成sitemap.xml
  • seo-head-component
    - 从next/head迁移至Metadata API

12. API Routes (MEDIUM)

12. API 路由(中)

  • api-route-handlers
    - Create Route Handlers in app/api
  • api-http-methods
    - Export named functions for HTTP methods
  • api-request-body
    - Parse request body properly
  • api-query-params
    - Access query parameters
  • api-headers-cookies
    - Access headers and cookies
  • api-response-types
    - Return proper response types
  • api-middleware
    - Implement middleware patterns
  • api-cors
    - Configure CORS properly
  • api-rate-limiting
    - Implement rate limiting
  • api-route-handlers
    - 在app/api中创建路由处理器
  • api-http-methods
    - 导出命名函数处理HTTP方法
  • api-request-body
    - 正确解析请求体
  • api-query-params
    - 访问查询参数
  • api-headers-cookies
    - 访问请求头与Cookie
  • api-response-types
    - 返回正确的响应类型
  • api-middleware
    - 实现中间件模式
  • api-cors
    - 正确配置CORS
  • api-rate-limiting
    - 实现请求限流

13. State Management (MEDIUM)

13. 状态管理(中)

  • state-context-client
    - Context requires 'use client'
  • state-zustand
    - Zustand works with hydration care
  • state-redux
    - Configure Redux with Next.js
  • state-jotai
    - Configure Jotai properly
  • state-recoil
    - Configure Recoil properly
  • state-url-state
    - Use URL for shareable state
  • state-server-state
    - Minimize client state with RSC
  • state-persistence
    - Handle state persistence
  • state-context-client
    - Context需搭配'use client'使用
  • state-zustand
    - 使用Zustand时注意水合问题
  • state-redux
    - 为Next.js配置Redux
  • state-jotai
    - 正确配置Jotai
  • state-recoil
    - 正确配置Recoil
  • state-url-state
    - 使用URL存储可共享状态
  • state-server-state
    - 利用RSC减少客户端状态
  • state-persistence
    - 处理状态持久化

14. Integrations (MEDIUM)

14. 集成(中)

  • integrations-sentry
    - Migrate Sentry error monitoring
  • integrations-sentry
    - 迁移Sentry错误监控

15. Testing (LOW)

15. 测试(低)

  • testing-jest-config
    - Update Jest configuration
  • testing-react-testing-library
    - RTL works the same
  • testing-server-components
    - Test Server Components
  • testing-client-components
    - Test Client Components
  • testing-async-components
    - Test async components
  • testing-mocking
    - Mock Next.js modules
  • testing-e2e-cypress
    - Configure Cypress for Next.js
  • testing-e2e-playwright
    - Configure Playwright for Next.js
  • testing-api-routes
    - Test API Route Handlers
  • testing-jest-config
    - 更新Jest配置
  • testing-react-testing-library
    - RTL使用方式保持不变
  • testing-server-components
    - 测试Server Components
  • testing-client-components
    - 测试客户端组件
  • testing-async-components
    - 测试异步组件
  • testing-mocking
    - 模拟Next.js模块
  • testing-e2e-cypress
    - 为Next.js配置Cypress
  • testing-e2e-playwright
    - 为Next.js配置Playwright
  • testing-api-routes
    - 测试API路由处理器

16. Build & Deployment (LOW)

16. 构建与部署(低)

  • build-scripts
    - Update build scripts
  • build-output
    - Understand build output
  • build-standalone
    - Configure standalone output
  • build-static-export
    - Configure static export
  • build-bundle-analysis
    - Analyze bundle size
  • build-vercel
    - Deploy to Vercel
  • build-docker
    - Configure Docker deployment
  • build-scripts
    - 更新构建脚本
  • build-output
    - 了解构建输出内容
  • build-standalone
    - 配置独立构建输出
  • build-static-export
    - 配置静态导出
  • build-bundle-analysis
    - 分析包体积
  • build-vercel
    - 部署至Vercel
  • build-docker
    - 配置Docker部署

17. Common Gotchas (HIGH)

17. 常见陷阱(高)

  • gotchas-window-undefined
    - Handle window/document in SSR
  • gotchas-hydration-mismatch
    - Fix hydration mismatches
  • gotchas-use-effect-timing
    - Understand useEffect in Next.js
  • gotchas-router-ready
    - Check router.isReady for query params
  • gotchas-dynamic-imports
    - Use next/dynamic properly
  • gotchas-api-routes-edge
    - Edge vs Node.js runtime
  • gotchas-middleware
    - Middleware runs on edge
  • gotchas-static-generation
    - Static vs dynamic rendering
  • gotchas-redirect
    - Handle redirects properly
  • gotchas-headers
    - Set response headers
  • gotchas-cookies
    - Handle cookies in RSC
  • gotchas-turbopack
    - Handle Turbopack compatibility issues
  • gotchas-empty-modules
    - Fix empty module exports for isolatedModules
  • gotchas-nullish-coalescing
    - Fix nullish coalescing runtime errors
  • gotchas-react19-class-components
    - Fix React 19 class component this binding
  • gotchas-react19-ref-prop
    - Handle React 19 ref prop changes
  • gotchas-websocket-optional-deps
    - Handle WebSocket native dependency bundling
  • gotchas-auth-race-conditions
    - Guard against auth/API race conditions
  • gotchas-auth-state-gating
    - Wait for auth state before checking roles
  • gotchas-configuration-idempotency
    - Ensure configuration idempotency with useRef
  • gotchas-hydration-nested-interactive
    - Avoid nested interactive elements
  • gotchas-router-push-timing
    - Never call router.push during render
  • gotchas-infinite-rerender
    - Prevent infinite re-render loops
  • gotchas-provider-hierarchy
    - Configure provider hierarchy correctly
  • gotchas-window-undefined
    - 在SSR中处理window/document对象
  • gotchas-hydration-mismatch
    - 修复水合不匹配问题
  • gotchas-use-effect-timing
    - 了解Next.js中useEffect的执行时机
  • gotchas-router-ready
    - 检查router.isReady以获取查询参数
  • gotchas-dynamic-imports
    - 正确使用next/dynamic
  • gotchas-api-routes-edge
    - 区分Edge与Node.js运行时
  • gotchas-middleware
    - 中间件运行在Edge环境
  • gotchas-static-generation
    - 区分静态与动态渲染
  • gotchas-redirect
    - 正确处理重定向
  • gotchas-headers
    - 设置响应头
  • gotchas-cookies
    - 在RSC中处理Cookie
  • gotchas-turbopack
    - 处理Turbopack兼容性问题
  • gotchas-empty-modules
    - 修复isolatedModules模式下的空模块导出问题
  • gotchas-nullish-coalescing
    - 修复空值合并运算符的运行时错误
  • gotchas-react19-class-components
    - 修复React 19类组件的this绑定问题
  • gotchas-react19-ref-prop
    - 处理React 19中ref属性的变更
  • gotchas-websocket-optional-deps
    - 处理WebSocket原生依赖打包问题
  • gotchas-auth-race-conditions
    - 防范认证/API竞态条件
  • gotchas-auth-state-gating
    - 等待认证状态就绪后再检查角色
  • gotchas-configuration-idempotency
    - 使用useRef确保配置幂等性
  • gotchas-hydration-nested-interactive
    - 避免嵌套交互式元素
  • gotchas-router-push-timing
    - 切勿在渲染期间调用router.push
  • gotchas-infinite-rerender
    - 防止无限重渲染循环
  • gotchas-provider-hierarchy
    - 正确配置提供者层级

Pre-Migration Checklist

迁移前检查清单

Before starting migration, scan the codebase for patterns that need special handling:
bash
undefined
开始迁移前,请扫描代码库以识别需要特殊处理的模式:
bash
undefined

Check 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.md
Each 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:
  1. Setup - Initialize Next.js project structure
  2. Routing - Convert React Router to file-based routing
  3. Environment Variables - Update env var prefixes
  4. Components - Add 'use client' directives where needed
  5. Data Fetching - Convert useEffect to server patterns
  6. Styling - Move global CSS, configure CSS-in-JS
  7. Images & Fonts - Adopt Next.js optimizations
  8. SEO - Migrate to Metadata API
  9. API Routes - Create Route Handlers
  10. Testing - Update test configuration
为获得最佳效果,请按以下顺序进行迁移:
  1. 项目设置 - 初始化Next.js项目结构
  2. 路由 - 将React Router转换为基于文件的路由
  3. 环境变量 - 更新环境变量前缀
  4. 组件 - 在需要的地方添加'use client'指令
  5. 数据获取 - 将useEffect转换为服务端模式
  6. 样式 - 迁移全局CSS,配置CSS-in-JS
  7. 图片与字体 - 采用Next.js优化方案
  8. SEO - 迁移至Metadata API
  9. API路由 - 创建路由处理器
  10. 测试 - 更新测试配置

Post-Migration Verification Checklist

迁移后验证清单

After migration, verify the application works correctly:
Core Functionality:
  • npm run dev
    starts Next.js dev server without errors
  • npm run build
    completes successfully
  • npm start
    runs the production build
  • 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
迁移完成后,请验证应用功能是否正常:
核心功能:
  • npm run dev
    可正常启动Next.js开发服务器,无错误
  • npm run build
    可成功完成
  • npm start
    可正常运行生产构建版本
  • 主应用可正常渲染
  • 所有路由均可访问
客户端功能:
  • localStorage/sessionStorage持久化功能正常
  • 暗黑模式或主题切换功能正常且可持久化
  • 客户端交互功能(表单、按钮、模态框)正常
  • 浏览器前进/后退导航功能正常
路由(如适用):
  • 基于哈希的路由正常工作(例如:
    #room=abc,key=xyz
  • 查询参数可正确读取
  • 动态路由可根据参数正确渲染
  • 无效路由可显示404页面
实时功能(如适用):
  • WebSocket连接可成功建立
  • 实时协作或更新功能正常
  • 断开后重连功能正常
集成功能(如适用):
  • 错误监控(Sentry)可捕获错误
  • 分析追踪可正常触发
  • 第三方认证(OAuth、Firebase)功能正常
  • 文件上传功能正常
PWA功能(如适用):
  • 生产构建版本中Service Worker可正常注册
  • 应用可被安装
  • 离线功能符合预期
性能:
  • 控制台无水合不匹配警告
  • 图片可正常加载并已优化
  • 字体加载无FOUT/FOIT问题
  • 无意外的控制台错误或警告