react项目如何上线
构建生产环境代码
运行命令生成优化后的生产环境代码,确保代码被压缩且去除调试信息:
npm run build
构建完成后会在项目根目录生成 build 文件夹,包含静态资源文件。
配置服务器
选择适合的服务器部署静态资源,常见方案如下:
- Nginx:配置指向
build文件夹的静态文件服务 - Node.js:使用
express或http-server托管build文件夹 - 云服务:如 AWS S3、Vercel、Netlify 等直接上传构建文件
Nginx 配置示例
编辑 Nginx 配置文件(如 /etc/nginx/conf.d/default.conf),添加以下内容:
server {
listen 80;
server_name your_domain.com;
root /path/to/react-project/build;
index index.html;
location / {
try_files $uri $uri/ /index.html;
}
}
重启 Nginx 使配置生效:
sudo systemctl restart nginx
处理路由问题
若使用 React Router,需确保服务器对所有路径返回 index.html,避免直接访问子路由时出现 404。上述 Nginx 配置中的 try_files 已解决此问题。
环境变量配置
生产环境变量需在构建前通过 .env.production 文件设置,变量名以 REACT_APP_ 开头:
REACT_APP_API_URL=https://api.example.com
重新运行 npm run build 使环境变量生效。
启用 HTTPS
使用 Let's Encrypt 生成免费 SSL 证书并配置 Nginx:
sudo certbot --nginx -d your_domain.com
自动更新证书可通过定时任务实现:
sudo certbot renew --dry-run
性能优化
- 启用 Brotli 或 Gzip 压缩
- 配置 HTTP 缓存头(如
Cache-Control) - 使用 CDN 加速静态资源加载
监控与错误跟踪
集成工具如 Sentry 或 LogRocket 捕获运行时错误:
npm install @sentry/react @sentry/tracing
在应用入口初始化:
import * as Sentry from "@sentry/react";
Sentry.init({
dsn: "YOUR_DSN_URL",
integrations: [new Sentry.BrowserTracing()],
tracesSampleRate: 0.2,
});
持续集成/部署 (CI/CD)
通过 GitHub Actions 或 GitLab CI 自动化部署流程。示例 GitHub Actions 配置:
name: Deploy
on: push
jobs:
build-and-deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- run: npm install && npm run build
- uses: peaceiris/actions-gh-pages@v3
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
publish_dir: ./build






