如何并行运行多个 npm 脚本?
并行跑多个 npm 脚本用 concurrently 或 npm-run-all:一条 npm run dev 同时启动服务、编译、监听。本文给出配置方法、跨平台注意事项与串行对比。
**用 concurrently(最流行)或 npm-run-all。**系统级也有 & 的野路子但有坑,后面说。
方案一:concurrently(推荐)
npm install -D concurrently
{
"scripts": {
"start": "node server.js",
"watch:css": "postcss src/*.css -w -o dist/",
"dev": "concurrently \"npm:start\" \"npm:watch:css\""
}
}
npm run dev # 两个任务同时跑,输出带颜色前缀区分
实用参数:-k(一个挂了杀掉其他)、-n server,css(自定义前缀名)、--raw。
方案二:npm-run-all
npm install -D npm-run-all
{
"scripts": {
"dev": "npm-run-all --parallel start watch:css",
"build": "npm-run-all --sequential clean compile"
}
}
--parallel 并行、--sequential 串行,支持通配符 npm-run-all -p "watch:*"。
野路子及其坑
"dev": "npm run start & npm run watch:css"
Unix shell 的 & 能并行,但:Windows cmd 不支持;Ctrl+C 杀不干净后台进程;输出混在一起。别在生产脚本里用。
Node 18+ 还有个原生替代:npm run start --workspaces 场景下配合 concurrently 仍是主流;单仓库多包场景可以用 turbo/nx 这类任务编排器。
常见问题(FAQ)
Q:并行任务里一个崩了,另一个还在跑怎么办?
concurrently 加 -k / --kill-others:任一任务退出就杀掉其余,避免留下孤儿进程。
Q:并行跑的输出交错看不清?
concurrently 默认给每个任务分配颜色和名字前缀;npm run dev -- --raw 可关闭前缀(看原始输出)。
Q:需要先跑完 A 再并行 B、C?
组合串行和并行:"dev": "npm-run-all -s build -p start watch"(先 build,再并行 start 和 watch)。