React项目生产环境打包与运行学习笔记
1. 项目初始化
- 工具:Create React App (CRA)
命令:
npx create-react-app my-app cd my-app- 说明:CRA提供开箱即用的配置,适合快速启动React项目。
2. 开发环境运行
命令:
npm start- 说明:启动开发服务器,默认端口3000,支持热重载。
3. 生产环境打包
命令:
npm run build- 说明:生成优化后的静态文件,存放在
build目录,适合部署到生产环境。
4. 生产环境运行
方法一:使用
serve工具安装:
npm install -g serve运行:
serve -s build- 说明:
serve是一个静态文件服务器,-s参数用于处理单页应用的路由问题,默认端口5000。
方法二:使用Node.js和Express
安装Express:
npm install express创建服务器文件(如
server.js):const express = require('express'); const path = require('path'); const app = express(); const port = process.env.PORT || 5000; // 提供静态文件 app.use(express.static(path.join(__dirname, 'build'))); // 处理React路由 app.get('*', (req, res) => { res.sendFile(path.join(__dirname, 'build', 'index.html')); }); app.listen(port, () => { console.log(`Server is running on port ${port}`); });运行:
node server.js- 说明:Express服务器提供静态文件服务,并处理React路由。
方法三:使用Nginx
安装Nginx:
sudo apt update sudo apt install nginx配置Nginx:
编辑Nginx配置文件(如
/etc/nginx/sites-available/default):server { listen 80; server_name your_domain_or_ip; root /path/to/your/react/build; index index.html; location / { try_files $uri /index.html; } }重启Nginx:
sudo systemctl restart nginx
- 说明:Nginx作为高性能Web服务器,适合生产环境部署。
5. 环境变量配置
创建
.env文件:REACT_APP_API_URL=https://api.example.com使用环境变量:
const apiUrl = process.env.REACT_APP_API_URL;- 说明:CRA支持在
.env文件中定义环境变量,需以REACT_APP_开头。
6. 性能优化
代码分割:
const OtherComponent = React.lazy(() => import('./OtherComponent'));Suspense:
<React.Suspense fallback={<div>Loading...</div>}> <OtherComponent /> </React.Suspense>- 说明:实现组件懒加载,优化初始加载性能。
7. 常用命令总结
开发:
npm start打包:
npm run build测试:
npm test格式化代码:
npm run format
总结
React项目生产环境打包与运行涉及多个步骤和工具,掌握这些知识有助于高效部署React应用。通过使用serve、Express或Nginx等工具,可以在生产环境中稳定运行React应用。同时,合理配置环境变量和优化性能,可以进一步提升项目质量和用户体验。