如何修复Heroku部署TypeScript+Node.js项目的H10崩溃错误?
部署TypeScript+Node.js项目到Heroku时出现H10崩溃错误的解决办法
错误日志
2023-02-03T09:02:57.853394+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=tech-up-api.herokuapp.com request_id=1fd2144d-0242-46b9-85f5-0212ee1d4997 fwd="31.148.135.0" dyno= connect= service= status=503 bytes= protocol=https
当前配置文件
tsconfig.json
{ "compilerOptions": { "target": "es2016", "module": "commonjs", "rootDir": "./src", "outDir": "./dist", "esModuleInterop": true, "forceConsistentCasingInFileNames": true, "strict": true, "skipLibCheck": true }, "include": ["src/**/*"] }
package.json
{ "name": "tech-up-api", "version": "1.0.0", "description": "", "main": "./src/server.ts", "scripts": { "build": "rm -rf ./dist/ && tsc", "postinstall": "tsc", "start": "node ./src/server.ts", "format": "prettier --write . --ignore-path .gitignore", "lint": "eslint . --ignore-path .gitignore", "fix-style": "npm run format && npm run lint -- --fix", "prepare": "husky install" }, "keywords": [], "author": "", "license": "ISC", "dependencies": { "cors": "^2.8.5", "dotenv": "^16.0.3", "express": "^4.18.2", "pg": "^8.9.0", "pg-hstore": "^2.3.4", "sequelize": "^6.28.0" }, "devDependencies": { "@mate-academy/eslint-config": "0.0.20", "@types/cors": "^2.8.13", "@types/express": "^4.17.16", "@types/node": "^18.11.18", "@typescript-eslint/eslint-plugin": "^5.50.0", "@typescript-eslint/parser": "^5.50.0", "eslint": "^8.33.0", "husky": "^8.0.3", "lint-staged": "^13.1.0", "nodemon": "^2.0.20", "prettier": "2.8.3", "ts-node": "^10.9.1", "typescript": "^4.9.5" }, "lint-staged": { "*.ts": "npm run fix-style" } }
项目结构

问题分析与修复步骤
1. 修正package.json的入口配置
Heroku无法直接运行TypeScript文件,必须先编译为JavaScript再执行。你当前的main字段和start脚本都指向TS源文件,这是启动失败的核心原因。
修改package.json中的以下内容:
- 将
main字段改为编译后的入口文件:"main": "./dist/server.js" - 将
start脚本改为运行编译后的JS文件:"start": "node ./dist/server.js"
2. 确保端口配置正确
Heroku会动态分配端口,代码中不能硬写固定端口(比如3000),需要监听process.env.PORT环境变量。
检查你的server.ts文件,确保启动代码类似:
const PORT = process.env.PORT || 3000; app.listen(PORT, () => { console.log(`Server running on port ${PORT}`); });
3. 验证编译流程
你已配置postinstall脚本自动执行tsc编译,这会在Heroku部署时自动生成dist目录。确保.gitignore没有包含dist目录(推荐让Heroku自行编译,而非提交编译产物)。
4. 查看详细崩溃日志
如果修改后仍出错,可通过以下命令查看启动时的具体错误信息(比如模块缺失、语法错误等):
heroku logs --tail
完成以上修改后,重新部署项目到Heroku即可解决H10崩溃问题。
内容的提问来源于stack exchange,提问作者Andrii Shymkiv
相关产品推荐
相关产品推荐

