react服务如何发布
打包 React 应用
使用 npm run build 或 yarn build 命令生成生产环境代码。打包后的文件会存放在 build 目录中,包含静态 HTML、CSS 和 JavaScript 文件。
选择部署方式
静态文件托管:适用于纯前端项目,可使用 Netlify、Vercel、GitHub Pages 等服务直接部署 build 文件夹。
服务器部署:将 build 文件夹上传至 Nginx、Apache 等 Web 服务器,配置根目录指向该文件夹。
配置服务器(以 Nginx 为例)
修改 Nginx 配置文件,指定根目录并处理路由:
server {
listen 80;
server_name yourdomain.com;
root /path/to/react-app/build;
index index.html;
location / {
try_files $uri $uri/ /index.html;
}
}
重启 Nginx 使配置生效:sudo systemctl restart nginx。
启用 HTTPS
使用 Let's Encrypt 免费证书,通过 Certbot 工具自动配置:
sudo certbot --nginx -d yourdomain.com
持续集成(CI/CD)
通过 GitHub Actions 或 GitLab CI 自动化部署。示例 GitHub Actions 配置:
name: Deploy React App
on: [push]
jobs:
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
环境变量处理
生产环境变量需在构建时注入,确保 .env.production 文件中配置正确的变量,例如:
REACT_APP_API_URL=https://api.example.com
构建后变量会被硬编码到静态文件中。
性能优化
启用代码分割(React.lazy + Suspense)、压缩资源(如 Brotli/Gzip)、使用 CDN 加速静态文件加载。
监控与错误跟踪
集成 Sentry 或 LogRocket 捕获运行时错误,分析用户行为及性能瓶颈。







