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

Heroku部署时如何运行多个npm脚本?解决仅执行首个脚本问题

Great question! The issue you're running into is that when you list multiple commands in a single npm script separated by spaces or semicolons, they run serially—and the first long-running foreground process (like your React dev server) blocks the rest from executing. Here are reliable ways to fix this on Heroku:

The cleanest approach is to use a tool built for running multiple commands simultaneously, like concurrently:

  • First, install it as a dependency (add --save-dev if you're only using it for development workflows):
    npm install concurrently --save
    
  • Update your package.json scripts to wrap your client and API commands with concurrently. For example:
    "scripts": {
      "client": "react-scripts start",
      "server": "node server.js",
      "start": "concurrently \"npm run client\" \"npm run server\""
    }
    
  • Keep your Procfile as web: npm run start—Heroku will execute this single command, which spawns both processes in parallel.

Production Best Practice: For a production deployment, you shouldn't run the React dev server. Instead, build your React app into static files first, then have your API server serve those files. This reduces overhead and only requires one running process:

"scripts": {
  "build": "react-scripts build",
  "start": "node server.js"
}

Add code to your API server (e.g., with Express) to serve the static build folder:

const path = require('path');
app.use(express.static(path.join(__dirname, 'build')));

You can use the & operator to push one process to the background, but ensure the final command runs in the foreground (so Heroku doesn't shut down the dyno):

"scripts": {
  "start": "npm run client & npm run server"
}

This works for quick testing, but has major downsides:

  • Logs from both processes will be mixed and harder to debug.
  • Heroku only monitors the foreground process—if the background client process crashes, it won't be restarted.
  • The React dev server isn't optimized for production performance.

Option 3: Use Separate Dynos (For Isolated Apps)

If your React client and API are fully independent, you can deploy them to separate Heroku dynos (each with its own Procfile and deployment). This adds cost but makes sense if the two apps need separate scaling or environments.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 03:44:14