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


当前回答

我的解决方案类似于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");
})();

其他回答

在父文件夹的package.json中:

"dev": "(cd api && start npm run start) & (cd ../client && start npm run start)"

这在windows中工作

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

package.json:

"scripts": {
  "start-watch": "...",
  "wp-server": "...",
  "dev": "npm-run-all --parallel start-watch wp-server"
}

更多信息:https://github.com/mysticatea/npm-run-all/blob/master/docs/npm-run-all.md

我已经从上面检查了几乎所有的解决方案,只有通过npm运行,我才能解决所有问题。与所有其他解决方案相比,主要优势是能够使用参数运行脚本。

{
  "test:static-server": "cross-env NODE_ENV=test node server/testsServer.js",
  "test:jest": "cross-env NODE_ENV=test jest",
  "test": "run-p test:static-server \"test:jest -- {*}\" --",
  "test:coverage": "npm run test -- --coverage",
  "test:watch": "npm run test -- --watchAll",
}

注意run-p是npm运行all的快捷方式--并行

这允许我使用npm-run-test:watch等参数运行命令。

编辑:

对于npm run-all,还有一个更有用的选项:

 -r, --race   - - - - - - - Set the flag to kill all tasks when a task
                            finished with zero. This option is valid only
                            with 'parallel' option.

将-r添加到npm run-all脚本中,以在一个进程完成代码0时终止所有进程。当您运行HTTP服务器和另一个使用该服务器的脚本时,这尤其有用。

  "test": "run-p -r test:static-server \"test:jest -- {*}\" --",

使用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"
  }

在windows cmd中,可以使用start:

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

以这种方式启动的每个命令都在其自己的窗口中启动。