「这是我参与2022首次更文挑战的第5天,活动详情查看:2022首次更文挑战」。
Dear,大家好,我是“前端小鑫同学”,😇长期从事前端开发,安卓开发,热衷技术,在编程路上越走越远~
背景介绍:
我们的node项目的脚本通通都是放在了
package.json
的scripts
节点下面,当我们要在一个命令执行完后接着去执行下一个命令的时候(如:打包后需要推送打包内容到服务器)就需要增加一条脚本并使用&&
进行拼接两条或多条命令来实现,并且符号&
在windows下的cmd.exe是不兼容的。
本期介绍的主角(npm-run-all):
今天主要想分享一个比较不错的Node包,我们可以通过提供的命令来制定脚本的执行计划,在你开发Node应用、Cli工具或着有复杂的多条script需要执行的时候会很有帮助,同样也是在掘金学到的知识再分享一下😂。
🍔有什么用?
- 简化脚本:
使用前: npm run clean && npm run build:css && npm run build:js && npm run build:html
使用后: npm-run-all clean build:*
- 跨平台:
主要是因为Windows用户通常使用的cmd.exe不支持&来拼接多条命令,但用户量又大。
🍟怎么安装?
Node版本>=4均可
命令:
npm install npm-run-all --save-dev
yarn add npm-run-all --dev
🌭怎么使用?
具体案例可参考文末整理的思维导图或项目的readme文件
-
定制复杂计划:npm-run-all
-
定制串行计划:run-s
- 案例:
使用前:
npm run clean && npm run lint && npm run build
使用后:
run-s clean lint build
- Examples
run-s build:*
run-s build:**
run-s lint clean build:**
run-s --silent --print-name lint clean build:**
run-s -sn lint clean build:**
- 定制并行计划:run-p
- 案例:
使用前:
npm run lint & npm run build
使用后:
run-p lint build
- Examples
run-p watch:**
run-p --print-label "build:** -- --watch"
run-p -l "build:** -- --watch"
run-p start-server start-browser start-electron
- 在NodeJS里面使用
综上所述的出的结论:
- 缺点1:脚本冗余;
- 缺点2:跨平台能力差。
命令支持:
- npm-run-all
- run-s:串行执行示例:
{
"scripts": {
"clean": "rimraf dist",
"lint": "eslint src",
"build": "babel src -o lib"
}
}
- npm run 执行:
npm run clean && npm run lint && npm run build
; - run-s执行:
run-s clean lint build
。
- run-p:并行执行示例:
{
"scripts": {
"clean": "rimraf dist",
"lint": "eslint src",
"build": "babel src -o lib"
}
}
- npm run 执行:
npm run lint & npm run build
; - run-p执行:
run-p lint build
。 - 提示:
- 代码非正常退出其他脚本将终止进程;
- & 操作符在windows系统的cmd.exe不被支持。
思维脑图:www.processon.com/view/link/6…
欢迎关注我的公众号“前端小鑫同学”,原创技术文章第一时间推送。