在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-run-all,这不是我的用例。

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

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

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

我已经从上面检查了几乎所有的解决方案,只有通过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 -- {*}\" --",

我有一个没有任何额外模块的跨平台解决方案。我正在寻找一个可以在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)将在所有平台上运行!

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

所以,这就是我所做的。

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

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