react 打包后如何启动
React 打包后启动方法
React 项目打包后生成的静态文件需要通过 Web 服务器来运行。以下是几种常见的启动方式:
使用 serve 工具启动
安装 serve 工具(全局或局部安装均可):
npm install -g serve
进入打包目录(通常是 build 或 dist)并启动服务:
serve -s build
-s 参数会处理单页应用的路由问题,确保直接访问 URL 时也能正确返回 index.html。
使用 http-server 启动
安装 http-server:
npm install -g http-server
启动服务:

http-server build
使用 Node.js 原生 http 模块
创建一个简单的 Node.js 服务器脚本(如 server.js):
const express = require('express');
const path = require('path');
const app = express();
app.use(express.static(path.join(__dirname, 'build')));
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'build', 'index.html'));
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
运行服务器:
node server.js
使用 Nginx 部署

配置 Nginx 指向打包目录(以 Ubuntu 为例):
server {
listen 80;
server_name your_domain.com;
root /path/to/your/build;
index index.html;
location / {
try_files $uri /index.html;
}
}
重启 Nginx 生效:
sudo systemctl restart nginx
使用 Docker 部署
创建 Dockerfile:
FROM nginx:alpine
COPY build /usr/share/nginx/html
构建并运行容器:
docker build -t react-app .
docker run -d -p 80:80 react-app
注意事项
- 确保打包命令已执行(通常为
npm run build或yarn build) - 生产环境建议使用 HTTPS 并配置正确的缓存策略
- 单页应用需确保服务器配置了 URL 回退到
index.html(即上述的try_files或-s参数) - 静态资源路径问题可通过在
package.json中添加"homepage": "."解决






