在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”

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

其他回答

我已经从上面检查了几乎所有的解决方案,只有通过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)将在所有平台上运行!

同时安装npm install

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

我认为最好的方法是使用npm运行如下:

1-npm install-g npm run-all<---将在全球范围内安装2-npm运行所有--并行服务器客户端

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