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

能否通过npm预钩子启动开发服务器并同时运行React项目?

Ah, I get it—you tried using a predev hook to fire up your nodemon proxy first, but since nodemon runs indefinitely (waiting for file changes), it blocks the dev script from ever executing. That’s such a common gotcha with npm’s pre-hooks—they’re designed to run serially, meaning they have to finish completely before the main script starts. Let’s work through the best fixes for this!

Pre-hooks are made for one-time setup tasks (like linting, cleaning build folders, or compiling assets)—not long-running processes like dev servers or proxies. Your original approach using run-p (from npm-run-all) is actually the right path; let’s just make it a bit more explicit and maintainable:

First, ensure you have npm-run-all installed (if not, run this in your terminal):

npm install --save-dev npm-run-all

Then update your package.json scripts to separate the tasks clearly:

"scripts": {
  "dev": "run-p proxy:start react:start",
  "proxy:start": "nodemon test-proxy.js",
  "react:start": "react-scripts start"
}

When you run npm run dev, both the nodemon proxy and React app will launch simultaneously. Even better: when you hit Ctrl+C to stop the dev environment, both processes will be terminated automatically—no leftover background processes to hunt down and kill manually.

If you’re set on leveraging the predev hook pattern, you can force nodemon to run in the background so the pre-hook exits and allows dev to start. Just be aware this has a major downside: stopping the React app won’t stop the proxy process—you’ll have to kill it manually later.

For Unix/Linux/macOS:

Add & to the end of the predev command to send the nodemon process to the background:

"scripts": {
  "predev": "nodemon test-proxy.js &",
  "dev": "react-scripts start"
}

For Windows:

Use start /B to run nodemon in the background without opening a new command window:

"scripts": {
  "predev": "start /B nodemon test-proxy.js",
  "dev": "react-scripts start"
}

⚠️ Heads up: When you stop the React app with Ctrl+C, the nodemon proxy will keep running in the background. On Unix, you can kill it with pkill node; on Windows, use Task Manager to find and end the node process.

Quick Recap of Why Your Original Pre-Hook Approach Failed

npm’s pre* hooks execute synchronously. They wait for the pre-script to exit with a success code before running the main script. Since nodemon is designed to run forever (watching for file changes), it never exits—so your dev script never gets its turn to run.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 04:05:58