如何配置根目录package.json将React+Node项目部署到同一Heroku应用
Heroku部署全栈项目根目录package.json配置方案
步骤1:初始化根目录package.json
在app父级文件夹根目录执行命令:npm init -y
执行后会自动生成默认的package.json文件,无需手动创建。
步骤2:配置核心脚本字段
打开生成的package.json,修改scripts字段,适配Heroku的部署规则:
"scripts": { "heroku-postbuild": "cd backend && npm install && cd ../frontend && npm install && npm run build", "start": "cd backend && npm start" }
字段说明:
heroku-postbuild是Heroku平台专属的构建钩子,部署时会自动执行:先安装后端依赖,再安装前端依赖、执行React项目的生产构建start是Heroku启动应用时默认执行的命令,这里直接调用后端的启动脚本即可
完整根目录package.json示例
{ "name": "fullstack-app", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "heroku-postbuild": "cd backend && npm install && cd ../frontend && npm install && npm run build", "start": "cd backend && npm start" }, "keywords": [], "author": "", "license": "ISC" }
额外注意事项
- 确保后端项目中已经配置静态资源指向,以Express为例,需要添加配置:
app.use(express.static(path.join(__dirname, '../frontend/build'))); // 所有非API请求返回前端页面,适配前端路由 app.get('*', (req, res) => { res.sendFile(path.join(__dirname, '../frontend/build', 'index.html')); }); - 根目录无需额外安装依赖,前后端的依赖会在构建阶段分别安装到对应子文件夹
- 根目录的
.gitignore需要添加node_modules、.env等不需要提交的文件
内容的提问来源于stack exchange,提问作者Saadi
相关产品推荐
相关产品推荐

