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


当前回答

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

其他回答

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

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

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

应该是:

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

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

使用npm运行多个并行脚本的分步指南。全局安装npm-run-all包

npm i -g npm-run-all

现在在package.json所在的项目中安装并保存此包

npm i npm-run-all --save-dev

现在以这种方式修改package.json文件中的脚本

"scripts": {
    "server": "live-server index.html",
    "watch": "node-sass scss/style.scss --watch",
    "all": "npm-run-all --parallel server watch"
},

现在运行此命令

npm run all

有关此包的详细信息,请参见给定的链接npm全部运行

在父文件夹的package.json中:

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

这在windows中工作

这对我有用

{
"start-express": "tsc && nodemon dist/server/server.js",
"start-react": "react-scripts start",
"start-both": "npm -p -r run start-react && -p -r npm run start-express"
}

客户端和服务器都是用typescript编写的。

React应用程序是使用typescript模板创建React应用程序,并位于默认src目录中。

Express位于服务器目录中,条目文件为server.js

typescript代码并转换成js,并放在dist目录中。

签出我的项目以获取更多信息:https://github.com/nickjohngray/staticbackeditor

更新:调用npm run-dev开始

{"server": "tsc-watch --onSuccess \"node ./dist/server/index.js\"",
"start-server-dev": "npm run build-server-dev && node src/server/index.js",
"client": "webpack-dev-server --mode development --devtool inline-source-map --hot",
"dev": "concurrently \"npm run build-server-dev\"  \"npm run server\" \"npm run client\""}

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