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


当前回答

只需将此npm脚本添加到根文件夹中的package.json文件。

{
  ...
  "scripts": {
    ...
    "start": "react-scripts start", // or whatever else depends on your project
    "dev": "(cd server && npm run start) & (cd ../client && npm run start)"
  }
}

其他回答

npm-run-all --parallel task1 task2

编辑:

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

如果将双&号替换为单&号,脚本将同时运行。

使用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全部运行

简单的节点脚本,让您无需太多麻烦。使用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);
});

您应该使用npm-run-all(或并发并行shell),因为它对启动和终止命令有更多的控制权。运算符&,|是个坏主意,因为在所有测试完成后,您需要手动停止它。

这是通过npm进行量角器测试的示例:

scripts: {
  "webdriver-start": "./node_modules/protractor/bin/webdriver-manager update && ./node_modules/protractor/bin/webdriver-manager start",
  "protractor": "./node_modules/protractor/bin/protractor ./tests/protractor.conf.js",
  "http-server": "./node_modules/http-server/bin/http-server -a localhost -p 8000",
  "test": "npm-run-all -p -r webdriver-start http-server protractor"
}

-p=并行运行命令。

-r=当其中一个命令结束时,退出代码为零,则终止所有命令。

运行npm运行测试将启动Selenium驱动程序,启动http服务器(为您提供文件)并运行量角器测试。完成所有测试后,它将关闭http服务器和selenium驱动程序。