Skip to content
返回部署

部署 React 单页应用

构建、打包并将 React 单页应用部署到静态主机,支持客户端路由与代码分割。

平台入门

为什么

React SPA 编译为静态 JS/CSS/HTML 资源,任何 CDN 都能低成本地通过全球边缘缓存提供服务。无服务器运行时意味着可预测的性能和极低的运维成本。

平台即服务采用率 2024 年增长 24%,团队从虚拟机管理转向 git push 部署。the cloud infrastructure market reached $330B in 2024, growing 22% year-over-year (Synergy Research),PaaS 层捕获了大多数新工作负载。

何时使用

适用于仪表盘、管理面板和高度交互的 UI 且无需 SSR 的场景。首屏 SEO 关键时避免使用 — 改用 Next.js/Remix。

如何做

1. 构建 — npm run build 生成 dist/ 含哈希资源 2. 配置 SPA 回退 — 所有路由返回 index.html(rewrites) 3. 设置 base path — vite.config base 或 PUBLIC_URL 用于子路径部署 4. 部署静态 — 上传 dist/ 到 Vercel/Netlify/S3+CloudFront 5. 缓存策略 — 哈希资源 immutable,index.html must-revalidate 6. 环境变量 — 构建时注入(REACT_APP_*)非运行时

示例

// vite.config.ts — SPA 构建配置 export default defineConfig({ base: "/app/", // 子路径部署 build: { outDir: "dist", sourcemap: false }, }); // vercel.json — SPA 回退重写 { "rewrites": [{ "source": "/(.*)", "destination": "/index.html" }] } // netlify.toml [[redirects]] from = "/*" to = "/index.html" status = 200 // S3 + CloudFront — 错误文档设为 index.html 实现 SPA 路由

常见问题

  • ⚠部署后白屏 — 忘记 SPA 回退重写,深链接 404
  • ⚠新部署后旧资源 — index.html 缓存过久,用户拿到旧 JS 块
  • ⚠生产环境变量未定义 — 运行时用 process.env 而非构建时 REACT_APP_ 前缀

最佳实践

  • ✓哈希资源 immutable 缓存(Cache-Control: max-age=31536000),index.html 短 TTL + must-revalidate
  • ✓用 React.lazy + Suspense 做路由级代码分割,保持初始包小
  • ✓设置健康检查和优雅关闭 — 处理 SIGTERM 以在退出前排空进行中的请求

常见问题解答