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

Heroku部署失败:sh: 1: ng: not found问题求助

解决Angular部署Heroku报错sh: 1: ng: not found

先看你的日志,发现Heroku执行的start命令是ng serve,但你提供的package.json里start已经改成node server.js了——这大概率是你修改了package.json但没推送到Heroku仓库,先把这个基础问题解决:

第一步:确保本地修改推送到Heroku

  • 先把所有修改的文件提交到git:
    git add package.json server.js
    git commit -m "Update deployment configuration"
    git push heroku master
    

如果推送后还是报错,再按下面的步骤逐一排查:

第二步:修复ng命令找不到的问题

  1. 删除不必要的preinstall脚本
    你的package.json里有"preinstall": "npm link @angular/cli ",这个在Heroku的隔离环境里没必要,反而可能导致链接失败,直接删掉这个字段。

  2. 用npx执行ng build
    把heroku-postbuild脚本改成npx ng build --prod,这样Heroku会自动从node_modules里找到ng命令执行,避免找不到的问题:

    "heroku-postbuild": "npx ng build --prod"
    

第三步:确保server.js正确配置

你的server.js需要正确serve Angular编译后的静态文件,下面是一个完整的示例(如果你的server.js还没正确写的话):

const express = require('express');
const path = require('path');
const app = express();

// 配置静态文件路径,对应Angular编译后的dist文件夹
app.use(express.static(path.join(__dirname, 'dist/the-lottery-genie-mean')));

// 捕获所有路由,返回Angular的index.html(解决单页应用路由问题)
app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname, 'dist/the-lottery-genie-mean/index.html'));
});

// 监听Heroku提供的端口,或者本地3000端口
const PORT = process.env.PORT || 3000;
app.listen(PORT, '0.0.0.0', () => {
  console.log(`Node app is running at port ${PORT}`);
});

注意:dist/the-lottery-genie-mean是Angular编译后的文件夹,名字和你package.json里的name字段一致,要确保路径正确。

另外,别忘了安装express依赖:

npm install express --save

然后提交这个修改到git再推送到Heroku。

第四步:检查依赖和引擎配置

  • 你的@angular/cli已经放在dependencies里(不是devDependencies),这是对的,因为Heroku默认不会安装devDependencies,所以必须把部署时需要的依赖放到dependencies里。
  • 你的engines字段指定了node和npm版本,Heroku会尽量匹配这个版本,如果遇到版本兼容问题,可以尝试更新到更稳定的LTS版本(比如node 14.x,但要确保和你的Angular版本兼容)。

做完这些步骤后,重新推送代码到Heroku,应该就能解决ng: not found的问题了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 08:51:47