在package.json中,我有两个脚本:

  "scripts": {
    "start-watch": "nodemon run-babel index.js",
    "wp-server": "webpack-dev-server",
  }

每次开始在Node.js中开发时,我都必须并行运行这两个脚本。我首先想到的是添加第三个脚本,如下所示:

"dev": "npm run start-watch && npm run wp-server"

…但这将在运行wp服务器之前等待开始监视完成。

如何并行运行这些?请记住,我需要查看这些命令的输出。此外,如果您的解决方案涉及构建工具,我宁愿使用gulf而不是gulf,因为我已经在另一个项目中使用了它。


当前回答

如果将双&号替换为单&号,脚本将同时运行。

其他回答

我有一个没有任何额外模块的跨平台解决方案。我正在寻找一个可以在cmd.exe和bash中使用的try-catch块。

解决方案是command1||command2,它似乎在两种环境中都一样。因此,OP的解决方案是:

"scripts": {
  "start-watch": "nodemon run-babel index.js",
  "wp-server": "webpack-dev-server",
  // first command is for the cmd.exe, second one is for the bash
  "dev": "(start npm run start-watch && start npm run wp-server) || (npm run start-watch & npm run wp-server)",
  "start": "npm run dev"
}

然后,简单的npm-start(和npm-run-dev)将在所有平台上运行!

使用同时调用的包。

npm i concurrently --save-dev

然后按如下方式设置npm run-dev任务:

"dev": "concurrently --kill-others \"npm run start-watch\" \"npm run wp-server\""

您还可以在特定脚本上使用pre和post作为前缀。

  "scripts": {
    "predev": "nodemon run-babel index.js &",
    "dev": "webpack-dev-server"
  }

然后运行:npm运行开发

使用concurrent可与共享输出流并行运行命令。为了便于区分哪个输出来自哪个进程,请使用缩短的命令格式,例如npm:wp-server。这将导致同时在每个输出行前面加上命令名。

在package.json中,脚本部分如下所示:

 "scripts": {
    "start": "concurrently \"npm:start-watch\" \"npm:wp-server\"",
    "start-watch": "nodemon run-babel index.js",
    "wp-server": "webpack-dev-server"
  }

如果将双&号替换为单&号,脚本将同时运行。