cra-to-next-migration by vercel-labs/migration-skills
npx skills add https://github.com/vercel-labs/migration-skills --skill cra-to-next-migration将 Create React App 项目转换为 Next.js 的全面迁移指南,涵盖路由、数据获取、组件、样式和部署。包含 17 个类别共 148 条规则,按迁移影响优先级排序。成功迁移后,应用程序应保持与迁移前相同的功能。
在以下情况下参考本指南:
使用 Next.js 16.x 或更高版本。请勿使用 Next.js 14.x 或 15.x。
开始迁移前,请检查当前最新版本:
npm info next version
在您的 package.json 中使用最新版本,并使用脱字符(^)允许次要/补丁版本更新。本迁移指南支持的最低版本是 ^16.0.0。
| 优先级 | 类别 | 影响 | 前缀 | 规则数量 |
|---|---|---|---|---|
| 1 | 项目设置 | 关键 |
广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
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 |
| 11 | SEO 与元数据 | 中 | seo- | 9 |
| 12 | API 路由 | 中 | api- | 9 |
| 13 | 状态管理 | 中 | state- | 8 |
| 14 | 集成 | 中 | integrations- | 1 |
| 15 | 测试 | 低 | testing- | 9 |
| 16 | 构建与部署 | 低 | build- | 7 |
| 17 | 常见问题 | 高 | gotchas- | 24 |
setup-initial-structure - 将 CRA 文件夹结构转换为 Next.js App Routersetup-package-json - 更新依赖项和脚本setup-next-config - 创建并配置 next.config.jssetup-typescript - 迁移 TypeScript 配置setup-eslint - 为 Next.js 更新 ESLintsetup-gitignore - 为 Next.js 更新 .gitignoredeps-react19-compatibility - 升级依赖项以确保与 React 19 兼容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 - 将 react-router Link 替换为 next/linkrouting-programmatic-navigation - 将 useNavigate 替换为 useRouterrouting-use-params - 将 useParams 替换为 Next.js paramsrouting-use-search-params - 正确替换 useSearchParamsrouting-nested-layouts - 将嵌套路由转换为布局routing-loading-states - 添加 loading.tsx 以实现 Suspenserouting-error-boundaries - 添加 error.tsx 以处理错误routing-not-found - 添加 not-found.tsx 以处理 404 页面routing-hash-based - 为纯客户端应用处理基于哈希的路由routing-protected-routes - 实现受保护路由模式data-useeffect-to-rsc - 将 useEffect 数据获取转换为服务器组件data-useeffect-to-ssr - 将 useEffect 转换为 getServerSidePropsdata-useeffect-to-ssg - 将 useEffect 转换为 getStaticPropsdata-client-fetch - 使用正确的模式保留客户端数据获取data-server-actions - 使用服务器操作进行数据变更data-revalidation - 配置数据重新验证策略data-streaming - 使用 Suspense 进行流式数据传输data-parallel-fetching - 在服务器上并行获取数据data-sequential-fetching - 处理顺序数据依赖data-caching - 配置获取缓存行为data-client-library-init - 在 useEffect 中初始化仅客户端库components-use-client - 为客户端组件添加 'use client' 指令components-server-default - 理解服务器组件是默认的components-boundary-placement - 策略性地放置客户端边界components-composition - 使用组合来最小化客户端 JScomponents-interleaving - 交错使用服务器和客户端组件components-props-serialization - 确保 props 是可序列化的components-children-pattern - 将服务器组件作为子组件传递components-context-providers - 正确处理 Context providerscomponents-third-party - 包装第三方客户端组件env-prefix-change - 将 REACT_APP_ 更改为 NEXT_PUBLIC_env-server-only - 对仅服务器变量使用无前缀变量env-runtime-config - 在需要时使用运行时配置env-local-files - 理解 .env 文件加载顺序env-build-time - 理解构建时与运行时环境变量env-validation - 验证必需的环境变量styling-global-css - 将全局 CSS 移动到 app/layout.tsxstyling-css-modules - CSS Modules 只需少量更改即可工作styling-sass - 配置 Sass 支持styling-tailwind - 配置 Tailwind CSSstyling-css-in-js - 处理 CSS-in-JS 库styling-styled-components - 为 SSR 配置 styled-componentsstyling-emotion - 为 SSR 配置 Emotionstyling-component-styles - 正确导入组件样式styling-postcss - 配置 PostCSSstyling-scss-global-syntax - 仅在 CSS Modules 中使用 :globalstyling-css-import-order - 在布局中控制 CSS 导入顺序styling-dark-mode-hydration - 处理深色模式,避免水合不匹配assets-public-folder - Public 文件夹工作方式相同assets-static-imports - 对资源使用静态导入assets-absolute-urls - 引用资源时无需 public 前缀assets-favicon - 将 favicon 放置在 app 目录中assets-manifest - 配置 Web 应用清单images-next-image - 将 img 替换为 next/imageimages-required-dimensions - 提供宽度和高度images-fill-prop - 使用 fill 属性实现响应式图像images-priority - 对 LCP 图像使用 priority 属性images-placeholder - 配置模糊占位符images-remote-patterns - 配置远程图像域名images-loader - 配置自定义图像加载器images-optimization - 理解自动优化fonts-next-font - 使用 next/font 进行优化fonts-google-fonts - 正确加载 Google 字体fonts-local-fonts - 加载本地字体文件fonts-variable-fonts - 配置可变字体fonts-font-display - 配置 font-display 策略fonts-preload - 理解自动字体预加载seo-metadata-api - 使用 Metadata API 替代 react-helmetseo-dynamic-metadata - 生成动态元数据seo-opengraph - 配置 Open Graph 元数据seo-twitter-cards - 配置 Twitter Card 元数据seo-json-ld - 添加结构化数据 (JSON-LD)seo-canonical - 设置规范 URLseo-robots - 配置 robots 元标签seo-sitemap - 生成 sitemap.xmlseo-head-component - 从 next/head 迁移到 Metadata APIapi-route-handlers - 在 app/api 中创建路由处理器api-http-methods - 为 HTTP 方法导出命名函数api-request-body - 正确解析请求体api-query-params - 访问查询参数api-headers-cookies - 访问请求头和 Cookieapi-response-types - 返回正确的响应类型api-middleware - 实现中间件模式api-cors - 正确配置 CORSapi-rate-limiting - 实现速率限制state-context-client - Context 需要 'use client' 指令state-zustand - Zustand 需注意水合问题state-redux - 在 Next.js 中配置 Reduxstate-jotai - 正确配置 Jotaistate-recoil - 正确配置 Recoilstate-url-state - 使用 URL 实现可共享状态state-server-state - 使用 RSC 最小化客户端状态state-persistence - 处理状态持久化integrations-sentry - 迁移 Sentry 错误监控testing-jest-config - 更新 Jest 配置testing-react-testing-library - RTL 工作方式相同testing-server-components - 测试服务器组件testing-client-components - 测试客户端组件testing-async-components - 测试异步组件testing-mocking - 模拟 Next.js 模块testing-e2e-cypress - 为 Next.js 配置 Cypresstesting-e2e-playwright - 为 Next.js 配置 Playwrighttesting-api-routes - 测试 API 路由处理器build-scripts - 更新构建脚本build-output - 理解构建输出build-standalone - 配置独立输出build-static-export - 配置静态导出build-bundle-analysis - 分析包大小build-vercel - 部署到 Vercelbuild-docker - 配置 Docker 部署gotchas-window-undefined - 在 SSR 中处理 window/documentgotchas-hydration-mismatch - 修复水合不匹配问题gotchas-use-effect-timing - 理解 Next.js 中的 useEffectgotchas-router-ready - 使用 router.isReady 检查查询参数gotchas-dynamic-imports - 正确使用 next/dynamicgotchas-api-routes-edge - Edge 与 Node.js 运行时gotchas-middleware - 中间件在 Edge 上运行gotchas-static-generation - 静态渲染与动态渲染gotchas-redirect - 正确处理重定向gotchas-headers - 设置响应头gotchas-cookies - 在 RSC 中处理 Cookiegotchas-turbopack - 处理 Turbopack 兼容性问题gotchas-empty-modules - 为 isolatedModules 修复空模块导出gotchas-nullish-coalescing - 修复空值合并运行时错误gotchas-react19-class-components - 修复 React 19 类组件的 this 绑定gotchas-react19-ref-prop - 处理 React 19 ref prop 变更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.pushgotchas-infinite-rerender - 防止无限重新渲染循环gotchas-provider-hierarchy - 正确配置 Provider 层级结构开始迁移前,请扫描代码库以查找需要特殊处理的模式:
# 检查 WebSocket 库(需要 webpack 回退配置)
grep -E "(socket\.io|\"ws\")" package.json
# 检查 SCSS :export 语法(可能需要 --webpack 标志)
grep -r ":export" --include="*.scss" src/
# 检查 SVG ReactComponent 导入(需要 SVGR 配置)
grep -r "ReactComponent" --include="*.ts" --include="*.tsx" src/
# 列出所有 REACT_APP_ 环境变量
grep -roh "REACT_APP_[A-Z_]*" --include="*.ts" --include="*.tsx" --include="*.js" --include="*.jsx" src/ | sort -u
# 检查使用对象表示法的 Redux extraReducers(对于 RTK v2,必须转换为 builder 模式)
grep -r "extraReducers:" --include="*.js" --include="*.jsx" --include="*.ts" --include="*.tsx" src/
# 检查需要更新的 /app/ 路径(如果使用了 (app) 路由组)
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 |
存在 ReactComponent SVG 导入 | assets-static-imports |
找到 REACT_APP_ 变量 | env-prefix-change |
找到 extraReducers: | state-redux(需要 RTK v2 builder 回调) |
导航中存在 /app/ 路径 | routing-route-groups(为路由组更新路径) |
阅读单个规则文件以获取详细说明和代码示例:
rules/setup-initial-structure.md
rules/routing-basic-pages.md
rules/data-useeffect-to-rsc.md
每个规则文件包含:
为获得最佳效果,请按以下顺序迁移:
迁移后,验证应用程序是否正常工作:
核心功能:
npm run dev 启动 Next.js 开发服务器且无错误npm run build 成功完成npm start 运行生产构建版本客户端功能:
路由(如适用):
#room=abc,key=xyz)实时功能(如适用):
集成(如适用):
PWA(如适用):
性能:
每周安装量
169
代码仓库
GitHub Stars
10
首次出现
2026年1月30日
安全审计
已安装于
codex159
cursor151
gemini-cli150
opencode149
github-copilot148
amp143
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.
Reference these guidelines when:
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:
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.
| Priority | Category | Impact | Prefix | Rules |
|---|---|---|---|---|
| 1 | Project Setup | CRITICAL | setup- | 6 |
| 2 | Dependencies | CRITICAL | deps- | 1 |
| 3 | Routing | CRITICAL | routing- | 17 |
| 4 | Data Fetching | CRITICAL | data- | 11 |
| 5 | Components | HIGH | components- |
setup-initial-structure - Convert CRA folder structure to Next.js App Routersetup-package-json - Update dependencies and scriptssetup-next-config - Create and configure next.config.jssetup-typescript - Migrate TypeScript configurationsetup-eslint - Update ESLint for Next.jssetup-gitignore - Update .gitignore for Next.jsdeps-react19-compatibility - Upgrade dependencies for React 19 compatibilityrouting-basic-pages - Convert components to file-based routesrouting-dynamic-routes - Use [param] syntax for dynamic segmentsrouting-catch-all-routes - Use [...slug] for catch-all routesrouting-optional-catch-all - Use [[...slug]] for optional catch-allrouting-route-groups - Use (group) folders for organizationrouting-parallel-routes - Use @slot for parallel routesrouting-intercepting-routes - Use (..) for intercepting routesrouting-link-component - Replace react-router Link with next/linkrouting-programmatic-navigation - Replace useNavigate with useRouterdata-useeffect-to-rsc - Convert useEffect fetches to Server Componentsdata-useeffect-to-ssr - Convert useEffect to getServerSidePropsdata-useeffect-to-ssg - Convert useEffect to getStaticPropsdata-client-fetch - Keep client fetches with proper patternsdata-server-actions - Use Server Actions for mutationsdata-revalidation - Configure data revalidation strategiesdata-streaming - Use Suspense for streaming datadata-parallel-fetching - Fetch data in parallel on serverdata-sequential-fetching - Handle sequential data dependenciescomponents-use-client - Add 'use client' directive for client componentscomponents-server-default - Understand server components are defaultcomponents-boundary-placement - Place client boundaries strategicallycomponents-composition - Use composition to minimize client JScomponents-interleaving - Interleave server and client componentscomponents-props-serialization - Ensure props are serializablecomponents-children-pattern - Pass server components as childrencomponents-context-providers - Handle Context providers properlycomponents-third-party - Wrap third-party client componentsenv-prefix-change - Change REACT APP to NEXT PUBLICenv-server-only - Use non-prefixed vars for server-onlyenv-runtime-config - Use runtime configuration when neededenv-local-files - Understand .env file loading orderenv-build-time - Understand build-time vs runtime env varsenv-validation - Validate required environment variablesstyling-global-css - Move global CSS to app/layout.tsxstyling-css-modules - CSS Modules work with minor changesstyling-sass - Configure Sass supportstyling-tailwind - Configure Tailwind CSSstyling-css-in-js - Handle CSS-in-JS librariesstyling-styled-components - Configure styled-components for SSRstyling-emotion - Configure Emotion for SSRstyling-component-styles - Import component styles properlystyling-postcss - Configure PostCSSassets-public-folder - Public folder works the same wayassets-static-imports - Use static imports for assetsassets-absolute-urls - Reference assets without public prefixassets-favicon - Place favicon in app directoryassets-manifest - Configure web app manifestimages-next-image - Replace img with next/imageimages-required-dimensions - Provide width and heightimages-fill-prop - Use fill for responsive imagesimages-priority - Use priority for LCP imagesimages-placeholder - Configure blur placeholdersimages-remote-patterns - Configure remote image domainsimages-loader - Configure custom image loadersimages-optimization - Understand automatic optimizationfonts-next-font - Use next/font for optimizationfonts-google-fonts - Load Google Fonts properlyfonts-local-fonts - Load local font filesfonts-variable-fonts - Configure variable fontsfonts-font-display - Configure font-display strategyfonts-preload - Understand automatic font preloadingseo-metadata-api - Use Metadata API instead of react-helmetseo-dynamic-metadata - Generate dynamic metadataseo-opengraph - Configure Open Graph metadataseo-twitter-cards - Configure Twitter Card metadataseo-json-ld - Add structured data (JSON-LD)seo-canonical - Set canonical URLsseo-robots - Configure robots meta tagsseo-sitemap - Generate sitemap.xmlseo-head-component - Migrate from next/head to Metadataapi-route-handlers - Create Route Handlers in app/apiapi-http-methods - Export named functions for HTTP methodsapi-request-body - Parse request body properlyapi-query-params - Access query parametersapi-headers-cookies - Access headers and cookiesapi-response-types - Return proper response typesapi-middleware - Implement middleware patternsapi-cors - Configure CORS properlyapi-rate-limiting - Implement rate limitingstate-context-client - Context requires 'use client'state-zustand - Zustand works with hydration carestate-redux - Configure Redux with Next.jsstate-jotai - Configure Jotai properlystate-recoil - Configure Recoil properlystate-url-state - Use URL for shareable statestate-server-state - Minimize client state with RSCstate-persistence - Handle state persistenceintegrations-sentry - Migrate Sentry error monitoringtesting-jest-config - Update Jest configurationtesting-react-testing-library - RTL works the sametesting-server-components - Test Server Componentstesting-client-components - Test Client Componentstesting-async-components - Test async componentstesting-mocking - Mock Next.js modulestesting-e2e-cypress - Configure Cypress for Next.jstesting-e2e-playwright - Configure Playwright for Next.jstesting-api-routes - Test API Route Handlersbuild-scripts - Update build scriptsbuild-output - Understand build outputbuild-standalone - Configure standalone outputbuild-static-export - Configure static exportbuild-bundle-analysis - Analyze bundle sizebuild-vercel - Deploy to Vercelbuild-docker - Configure Docker deploymentgotchas-window-undefined - Handle window/document in SSRgotchas-hydration-mismatch - Fix hydration mismatchesgotchas-use-effect-timing - Understand useEffect in Next.jsgotchas-router-ready - Check router.isReady for query paramsgotchas-dynamic-imports - Use next/dynamic properlygotchas-api-routes-edge - Edge vs Node.js runtimegotchas-middleware - Middleware runs on edgegotchas-static-generation - Static vs dynamic renderinggotchas-redirect - Handle redirects properlyBefore starting migration, scan the codebase for patterns that need special handling:
# Check for WebSocket libraries (needs webpack fallback config)
grep -E "(socket\.io|\"ws\")" package.json
# Check for SCSS :export syntax (may need --webpack flag)
grep -r ":export" --include="*.scss" src/
# Check for SVG ReactComponent imports (needs SVGR config)
grep -r "ReactComponent" --include="*.ts" --include="*.tsx" src/
# List all REACT_APP_ environment variables
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)
grep -r "extraReducers:" --include="*.js" --include="*.jsx" --include="*.ts" --include="*.tsx" src/
# Check for /app/ paths that need updating if using (app) route group
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 |
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:
For best results, migrate in this order:
After migration, verify the application works correctly:
Core Functionality:
npm run dev starts Next.js dev server without errorsnpm run build completes successfullynpm start runs the production buildClient-Side Features:
Routing (if applicable):
#room=abc,key=xyz)Real-Time Features (if applicable):
Integrations (if applicable):
PWA (if applicable):
Performance:
Weekly Installs
169
Repository
GitHub Stars
10
First Seen
Jan 30, 2026
Security Audits
Gen Agent Trust HubPassSocketPassSnykWarn
Installed on
codex159
cursor151
gemini-cli150
opencode149
github-copilot148
amp143
UI组件模式实战指南:构建可复用React组件库与设计系统
10,700 周安装
Azure 存储服务完整指南:Blob、文件、队列、表存储及Data Lake使用教程
133,100 周安装
Azure资源可视化工具 - 自动生成架构图,分析资源依赖关系
133,400 周安装
Azure云迁移工具:AWS Lambda到Azure Functions自动评估与代码迁移指南
133,200 周安装
Azure Application Insights 检测指南:ASP.NET Core、Node.js、Python 应用遥测配置教程
133,300 周安装
Azure部署指南:从验证到执行的完整流程与最佳实践
133,300 周安装
Azure AI 服务指南:AI Search、Speech、OpenAI、文档智能功能与SDK
133,300 周安装
| 9 |
| 6 | Environment Variables | HIGH | env- | 6 |
| 7 | Styling | HIGH | styling- | 12 |
| 8 | Public Assets | MEDIUM | assets- | 5 |
| 9 | Images | MEDIUM | images- | 8 |
| 10 | Fonts | MEDIUM | fonts- | 6 |
| 11 | SEO & Metadata | MEDIUM | seo- | 9 |
| 12 | API Routes | MEDIUM | api- | 9 |
| 13 | State Management | MEDIUM | state- | 8 |
| 14 | Integrations | MEDIUM | integrations- | 1 |
| 15 | Testing | LOW | testing- | 9 |
| 16 | Build & Deploy | LOW | build- | 7 |
| 17 | Common Gotchas | HIGH | gotchas- | 24 |
routing-use-params - Replace useParams with Next.js paramsrouting-use-search-params - Replace useSearchParams properlyrouting-nested-layouts - Convert nested routes to layoutsrouting-loading-states - Add loading.tsx for suspenserouting-error-boundaries - Add error.tsx for error handlingrouting-not-found - Add not-found.tsx for 404 pagesrouting-hash-based - Handle hash-based routing for client-only appsrouting-protected-routes - Implement protected route patternsdata-caching - Configure fetch caching behaviordata-client-library-init - Initialize client-only libraries in useEffectstyling-scss-global-syntax - Use :global only in CSS Modulesstyling-css-import-order - Control CSS import order in layoutsstyling-dark-mode-hydration - Handle dark mode without hydration mismatchgotchas-headers - Set response headersgotchas-cookies - Handle cookies in RSCgotchas-turbopack - Handle Turbopack compatibility issuesgotchas-empty-modules - Fix empty module exports for isolatedModulesgotchas-nullish-coalescing - Fix nullish coalescing runtime errorsgotchas-react19-class-components - Fix React 19 class component this bindinggotchas-react19-ref-prop - Handle React 19 ref prop changesgotchas-websocket-optional-deps - Handle WebSocket native dependency bundlinggotchas-auth-race-conditions - Guard against auth/API race conditionsgotchas-auth-state-gating - Wait for auth state before checking rolesgotchas-configuration-idempotency - Ensure configuration idempotency with useRefgotchas-hydration-nested-interactive - Avoid nested interactive elementsgotchas-router-push-timing - Never call router.push during rendergotchas-infinite-rerender - Prevent infinite re-render loopsgotchas-provider-hierarchy - Configure provider hierarchy correctlyextraReducers: found | state-redux (RTK v2 builder callback required) |
/app/ paths in navigation | routing-route-groups (update paths for route groups) |