react如何本地开启服务器
使用 Create React App 内置命令
在项目根目录下运行以下命令启动开发服务器:
npm start
或使用 yarn:
yarn start
默认会在 http://localhost:3000 启动,自动打开浏览器并热更新代码。
自定义配置端口
修改启动端口可通过以下方式:
- 在
package.json中修改启动脚本:"scripts": { "start": "set PORT=4000 && react-scripts start" } - 或直接运行时指定环境变量:
PORT=4000 npm start
使用 HTTPS 协议
需要本地 HTTPS 时,设置环境变量:

HTTPS=true npm start
需提前安装本地证书(如 mkcert 工具生成的证书)。
通过自定义 Express 服务器
创建 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'));
});
app.listen(4000, () => console.log('Server running on port 4000'));
先构建项目:

npm run build
再启动服务器:
node server.js
使用 http-server 快速启动
全局安装 http-server:
npm install -g http-server
构建项目后启动:
npm run build
http-server build -p 3000
解决常见问题
- 端口占用:通过
lsof -i :3000查找占用进程,或更换端口 - HMR 不工作:检查
.env文件中是否设置FAST_REFRESH=false - 生产环境模拟:使用
serve -s build命令测试构建结果





