在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"

其他回答

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

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

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

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

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

快速解决方案

在这种情况下,我认为最好的办法是,如果该脚本用于专用模块,只在基于*nix的机器上运行,则可以使用控制运算符来分叉进程,如下所示:&

在部分package.json文件中执行此操作的示例:

{
  "name": "npm-scripts-forking-example",
  "scripts": {
    "bundle": "watchify -vd -p browserify-hmr index.js -o bundle.js",
    "serve":  "http-server -c 1 -a localhost",
    "serve-bundle": "npm run bundle & npm run serve &"
  }

然后通过npm-run-serve捆绑包并行执行它们。您可以增强脚本以将分叉进程的pid输出到文件,如下所示:

"serve-bundle": "npm run bundle & echo \"$!\" > build/bundle.pid && npm run serve & echo \"$!\" > build/serve.pid && npm run open-browser",

谷歌类似于bash控件操作符,用于分叉,以了解更多关于其工作原理的信息。我还提供了一些关于在Node项目中利用Unix技术的进一步上下文:

进一步的上下文RE:Unix工具和Node.js

如果您不使用Windows,Unix工具/技术通常可以很好地使用Node脚本实现某些功能,因为:

Node.js中的很多都很好地模仿了Unix原理您使用的是*nix(包括OS X),而NPM使用的是shell

Nodeland中用于系统任务的模块通常也是Unix工具的抽象或近似,从fs到流。

Windows CMD的简单本机方式

"start /b npm run bg-task1 && start /b npm run bg-task2 && npm run main-task"

(启动/b表示在后台启动)

这对我有用

{
"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脚本添加到根文件夹中的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)"
  }
}