react项目代码如何上生产环境
构建生产环境代码
运行以下命令生成优化后的生产版本代码,该命令会启用代码压缩、tree-shaking等优化措施:
npm run build
构建完成后会在项目根目录生成build文件夹,包含所有静态资源文件。
配置环境变量
创建.env.production文件定义生产环境专用变量,确保包含必要的API端点、密钥等配置:
REACT_APP_API_URL=https://api.example.com
REACT_APP_ENV=production
服务器部署配置
对于Nginx服务器,添加以下配置处理单页应用路由和静态资源:

server {
listen 80;
server_name yourdomain.com;
location / {
root /path/to/build;
try_files $uri /index.html;
}
}
启用HTTPS
使用Let's Encrypt获取免费SSL证书并配置强制HTTPS:
sudo certbot --nginx -d yourdomain.com
在Nginx配置中添加301重定向:

server {
listen 80;
server_name yourdomain.com;
return 301 https://$host$request_uri;
}
性能优化
在index.html中添加预加载关键资源:
<link rel="preload" href="/static/js/main.[hash].js" as="script">
<link rel="preload" href="/static/css/main.[hash].css" as="style">
监控与错误追踪
集成Sentry进行前端错误监控,在项目入口文件添加:
import * as Sentry from '@sentry/react';
Sentry.init({
dsn: 'YOUR_DSN',
environment: 'production'
});
持续集成部署
配置GitHub Actions自动化部署流程示例:
name: Deploy
on:
push:
branches: [main]
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





