在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-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驱动程序。

其他回答

使用同时调用的包。

npm i concurrently --save-dev

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

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

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

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

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

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

在windows cmd中,可以使用start:

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

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

同时安装npm install

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

您还可以在特定脚本上使用pre和post作为前缀。

  "scripts": {
    "predev": "nodemon run-babel index.js &",
    "dev": "webpack-dev-server"
  }

然后运行:npm运行开发