在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,因为我已经在另一个项目中使用了它。


当前回答

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

要使其工作,必须在命令上使用start。其他人已经说明了,但这是它的工作原理,您的代码如下:

“dev”:“npm运行开始监视&&npm运行wp服务器”

应该是:

“dev”:“start npm run start watch&&start npm run-wp server”

这将做的是,它将为每个命令打开一个单独的实例并同时处理它们,就您的初始问题而言,这不应该是一个问题。我为什么这么说?这是因为当您只运行一条语句时,这两个实例都会自动打开,这是您的初始目标。

其他回答

我的解决方案类似于Piittis,尽管我在使用Windows时遇到了一些问题。所以我必须验证win32。

const { spawn } = require("child_process");

function logData(data) {
    console.info(`stdout: ${data}`);
}

function runProcess(target) {
    let command = "npm";
    if (process.platform === "win32") {
        command = "npm.cmd"; // I shit you not
    }
    const myProcess = spawn(command, ["run", target]); // npm run server

    myProcess.stdout.on("data", logData);
    myProcess.stderr.on("data", logData);
}

(() => {
    runProcess("server"); // package json script
    runProcess("client");
})();

在Linux上只使用shell脚本。

"scripts": {
  "cmd": "{ trap 'trap \" \" TERM; kill 0; wait' INT TERM; } && blocking1 & blocking2 & wait"
}

npm运行命令然后^C会杀死孩子,等待干净的出口。

在我的例子中,我有两个项目,一个是UI,另一个是API,它们在各自的package.json文件中都有自己的脚本。

所以,这就是我所做的。

npm run --prefix react start&  npm run --prefix express start&

我遇到了&和|的问题,分别是退出状态和抛出错误。

其他解决方案希望使用给定的名称运行任何任务,例如npm-run-all,这不是我的用例。

所以我创建了npm运行并行,它异步运行npm脚本,并在完成后返回报告。

所以,对于您的脚本,它应该是:

npm运行并行wp服务器启动监视

同时安装npm install

"scripts": {
    "start:build": "tsc -w",
    "start:run": "nodemon build/index.js",
    "start": "concurrently  npm:start:*"
  },