前端工程化多任务并发利器-concurrently

简介

concurrently 是一个运行并发任务的工具库,可以帮助我们在 Node.js 中轻松管理多个异步任务。

安装

使用 npm 安装 concurrently:

1
npm install concurrently --save-dev

使用场景

同时运行多个 npm scripts

package.json:

1
2
3
"scripts": {
"start": "concurrently \"npm run server\" \"npm run client\""
}

运行 npm start将同时运行 npm run server 和 npm run client。

顺序运行 npm scripts

package.json:

1
2
3
"scripts": {
"prepare": "concurrently npm:install:package-lock npm:install"
}

运行 npm run prepare将先运行 npm:install:package-lock,完成后再运行 npm:install。

运行命令和 npm scripts

package.json:

1
2
3
"scripts": {
"start": "concurrently \"npm run client\" \"cd server && nodemon server.js\""
}

运行 npm start 将同时运行 npm run client 和 cd server && nodemon server.js。

传递环境变量和输入

package.json:

1
2
3
"scripts": {
"start": "concurrently \"npm run server\" \"npm run client\" --kill-others-on-fail --env NODE_ENV=production"
}

运行 npm start 将设置 NODE_ENV=production环境变量传递给 npm run server 和 npm run client。

–kill-others-on-fail 选项指定如果其中一个任务失败,其他运行的任务也会被 killed。

你也可以在运行 concurrently 时输入 ENV_VAR=value 来设置环境变量。

前缀日志

package.json:

1
2
3
"scripts": {
"start": "concurrently \"npm run server\" \"npm run client\" --names \"SERVER,CLIENT\""
}

运行 npm start 将为日志加上 [SERVER] 和 [CLIENT] 前缀,区分来自哪个任务的日志。

案例

一个常见的 concurrently 使用案例是同时运行前端开发服务器和后端 API 服务器。

package.json:

1
2
3
4
5
"scripts": {
"client": "cd client && npm start",
"server": "cd server && npm run dev",
"start": "concurrently \"npm run client\" \"npm run server\" --kill-others-on-fail"
}

运行 npm start 将同时启动前端开发服务器在端口 3000 和后端 API 服务器在端口 5000。如果任一服务器关闭,另一个也会关闭。

本文永久链接: https://www.mulianju.com/concurrently/