如何部署react应用
构建生产版本
使用React官方脚手架工具Create React App(CRA)构建优化后的生产版本。在项目根目录运行以下命令生成build文件夹:
npm run build
该命令会压缩代码、移除开发依赖并生成静态资源文件。
静态服务器部署
将build文件夹内容上传至支持静态托管的服务:
- Vercel:直接拖拽
build文件夹到Vercel控制台 - Netlify:在部署设置中指定
build为发布目录 - GitHub Pages:添加
homepage字段到package.json后运行:npm install gh-pages --save-dev npm run deploy
Node.js服务器部署
使用Express.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);
将上述代码保存为server.js,与build文件夹同级,然后运行:
node server.js
Docker容器化
创建Dockerfile:
FROM node:alpine
WORKDIR /app
COPY package.json .
RUN npm install
COPY . .
RUN npm run build
FROM nginx
COPY --from=0 /app/build /usr/share/nginx/html
EXPOSE 80
构建并运行容器:
docker build -t react-app .
docker run -p 80:80 react-app
环境变量配置
生产环境变量需以REACT_APP_前缀声明在.env.production文件:
REACT_APP_API_URL=https://api.example.com
构建时会自动注入到编译后的代码中。

性能优化
- 启用代码分割:
const OtherComponent = React.lazy(() => import('./OtherComponent')); - 添加
serviceWorker.js实现离线缓存(CRA项目默认包含) - 使用
CompressionPlugin进一步减小资源体积






