云计算百科
云计算领域专业知识百科平台

Concurrently 一键启动客户端和服务器

目录

简介

安装

使用场景

同时运行多个 npm scripts

顺序运行 npm scripts

运行命令和 npm scripts

传递环境变量和输入

前缀日志

案例


简介

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] 前缀,区分来自哪个任务的日志。

案例

在日常的全栈开发过程中,往往会同时启动服务器和客户端工程,分别启动服务器和客户端往往会不可避免的造成一定时间浪费和开发流程繁杂.本着能躺着就别坐着的原则,在万能的npm库中找到了concurrently


如下面package.json内的脚本代码所示,concurrently将服务端及客户端项目的启动合并在一起了.妈妈再也不用担心我浪费时间在启动项目上了😊.

–prefix 的作用是:编译的时候用来指定程序存放路径 。

NODE_ENV=development的作用是:设置环境变量

concurrently的作用为:合并命令

"scripts": {
"start": "node server.js",
"server": "NODE_ENV=development nodemon server.js",
"web-install": "npm install –prefix ../web",
"web": "npm start –prefix ../web",
"dev": "concurrently \\"npm run server\\" \\"npm run web\\""
},

赞(0)
未经允许不得转载:网硕互联帮助中心 » Concurrently 一键启动客户端和服务器
分享到: 更多 (0)

评论 抢沙发

评论前必须登录!