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


当前回答

在Linux上只使用shell脚本。

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

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

其他回答

在windows cmd中,可以使用start:

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

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

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

来一份老式的Makefile怎么样?

这允许您进行大量控制,包括如何管理子外壳、脚本之间的依赖关系等。


# run both scripts
start: server client

# start server and use & to background it
server:
    npm run serve &

# start the client
client:
    npm start

调用此Makefile,然后您可以键入

让一切开始。因为当您使用ctrl-C时,服务器命令实际上是在start命令的子进程中运行的,所以服务器命令也会停止,这与您自己在shell中备份不同。Make还可以完成命令行,至少在我使用的shell上是这样。另外,第一个命令将始终运行,因此您可以在这里自己键入make。

我总是在我的项目中加入一个makefile,这样我就可以在以后快速扫描每个项目的所有常用命令和参数。

我的解决方案类似于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");
})();
npm-run-all --parallel task1 task2

编辑:

您需要事先安装npm runall。还请检查此页面以了解其他使用情况。