You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React.js应用部署至Heroku失败问题求助

解决Heroku部署React.js应用的失败问题

我来帮你搞定这个Heroku部署的坑!从你的错误日志来看,主要是两个问题在搞事情:Node版本没正确指定,还有打包后的静态资源托管配置需要调整,咱们一步步来修复:

1. 给Heroku明确指定Node.js和npm版本

Heroku需要知道你要用哪个版本的Node,你之前把node放在dependencies里是不对的,得单独加个engines字段到package.json里。先把dependencies里的"node": "9.4.0"删掉,然后在package.json里添加:

"engines": {
  "node": "9.4.0",
  "npm": "5.6.0"
}

提示:npm版本可以用你本地的,在终端敲npm -v就能看到自己当前的版本号,填进去就行

2. 调整Webpack打包路径和Server静态资源托管

你的postinstall脚本是webpack -p,要确保Webpack配置文件(webpack.config.js)里的输出路径是dist文件夹(如果还没配置的话赶紧加上):

module.exports = {
  // ...其他配置
  output: {
    path: __dirname + '/dist',
    filename: 'bundle.js'
  }
}

然后修改你的server.js,让Express正确托管打包后的静态文件,别再直接托管根目录了:

const express = require('express');
const path = require('path');
const port = process.env.PORT || 8080;
const app = express();

// 托管dist文件夹里的打包后资源
app.use(express.static(path.join(__dirname, 'dist')));

// 所有请求都返回dist里的index.html(SPA路由需要)
app.get('*', (req, res) => {
  res.sendFile(path.resolve(__dirname, 'dist', 'index.html'));
});

app.listen(port);
console.log('Server started');

如果你的index.html原本在根目录,记得把它复制到dist文件夹,或者在Webpack里加个插件自动复制过去,比如html-webpack-plugin

3. 重新部署的操作步骤

先在本地验证没问题:

  • 执行npm run postinstall,看看dist文件夹里是不是生成了bundle.js和index.html
  • 运行node server.js,访问localhost:8080确认应用正常运行

然后提交修改推到Heroku:

git add package.json server.js webpack.config.js
git commit -m "Fix Heroku deploy: specify node version and correct static asset path"
git push heroku master

万一还是有问题?

如果greq: command not found的错误还存在,大概率是Heroku缓存的旧环境搞的鬼,清空缓存再试:

heroku plugins:install heroku-repo
heroku repo:purge_cache -a 你的应用名称
git push heroku master

内容的提问来源于stack exchange,提问作者user8359832

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:43:18