部署MERN应用至Heroku遇build脚本缺失及index.html找不到问题
MERN应用部署Heroku问题排查与解决
问题概述
- 部署MERN应用到Heroku时,收到提示:脚本'build'未找到
- 通过
heroku run bash进入frontend目录执行dir,发现目录为空 - 将
npm run build改为npm run-script后部署无报错,但访问页面时提示index.html无法找到 - .gitignore文件未包含/build路径
目录结构说明
根目录 ├── api/ │ ├── index.js │ └── package.json └── frontend/ ├── package.json └── React项目相关文件(src/、public/等)
提供的代码片段
api目录下的package.json
{ "name": "api", "version": "1.0.0", "description": "", "main": "index.js", "type": "module", "scripts": { "start": "node index.js", "heroku-postbuild": "cd frontend && npm install && npm run build" }, "engines": { "node": "18.x", "npm":"9.x" } }
api目录下的index.js(静态文件配置部分)
app.use(express.static(path.join(__dirname, "frontend/build"))); app.get("*", (req, res) => { res.sendFile(path.join(__dirname, "frontend/build", "index.html")); });
问题排查与解决步骤
1. 修复frontend目录为空的问题
Heroku拉取的代码中frontend目录为空,大概率是该目录的文件未提交到Git仓库:
- 执行
git status检查根目录下的frontend文件是否未被跟踪,若有未提交文件,执行git add . && git commit -m "add frontend files" - 检查根目录的
.gitignore,确保没有包含frontend/或frontend下关键文件的忽略规则
2. 解决"脚本'build'未找到"错误
该错误是因为frontend目录的package.json缺少build脚本,需确保其scripts字段包含:
"scripts": { "start": "react-scripts start", "build": "react-scripts build", "test": "react-scripts test", "eject": "react-scripts eject" }
如果是自定义React项目,替换为对应的打包命令即可。
3. 修正Heroku Postbuild脚本路径
当前api目录的heroku-postbuild脚本路径错误,因为api本身在子目录,需要先回到根目录再进入frontend,修改为:
"heroku-postbuild": "cd ../frontend && npm install && npm run build"
4. 修正静态文件路径
ES模块中__dirname不默认存在,同时需要调整路径指向根目录下的frontend/build:
import path from 'path'; import { fileURLToPath } from 'url'; // 定义__dirname(ES模块环境下) const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); // 修正静态文件路径 app.use(express.static(path.join(__dirname, "../frontend/build"))); app.get("*", (req, res) => { res.sendFile(path.join(__dirname, "../frontend/build", "index.html")); });
5. 重新部署验证
执行以下命令重新部署:
git add . && git commit -m "fix deployment configs" && git push heroku main
部署完成后,通过heroku run bash进入容器,检查../frontend/build目录是否存在index.html文件,确认打包成功。
内容的提问来源于stack exchange,提问作者Captai-N
相关产品推荐
相关产品推荐

