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


当前回答

如果您使用的是类似UNIX的环境,请使用&作为分隔符:

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

否则,如果您对跨平台解决方案感兴趣,可以使用npm-run-all模块:

"dev": "npm-run-all --parallel start-watch wp-server"

其他回答

这对我有用

{
"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\""}

使用同时调用的包。

npm i concurrently --save-dev

然后按如下方式设置npm run-dev任务:

"dev": "concurrently --kill-others \"npm run start-watch\" \"npm run wp-server\""

简单的节点脚本,让您无需太多麻烦。使用readline组合输出,使行不会被损坏。

const { spawn } = require('child_process');
const readline = require('readline');

[
  spawn('npm', ['run', 'start-watch']),
  spawn('npm', ['run', 'wp-server'])
].forEach(child => {
    readline.createInterface({
        input: child.stdout
    }).on('line', console.log);

    readline.createInterface({
        input: child.stderr,
    }).on('line', console.log);
});

在windows cmd中,可以使用start:

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

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

我遇到了&和|的问题,分别是退出状态和抛出错误。

其他解决方案希望使用给定的名称运行任何任务,例如npm-run-all,这不是我的用例。

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

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

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