zl程序教程

您现在的位置是:首页 >  Java

当前栏目

【分享】并行或串行运行多个NPM脚本的CLI工具

2023-02-18 16:41:28 时间

Dear,大家好,我是“前端小鑫同学”,?长期从事前端开发,安卓开发,热衷技术,在编程路上越走越远~

背景介绍:

我们的node项目的脚本通通都是放在了package.jsonscripts节点下面,当我们要在一个命令执行完后接着去执行下一个命令的时候(如:打包后需要推送打包内容到服务器)就需要增加一条脚本并使用&&进行拼接两条或多条命令来实现,并且符号&在windows下的cmd.exe是不兼容的。

本期介绍的主角(npm-run-all):

今天主要想分享一个比较不错的Node包,我们可以通过提供的命令来制定脚本的执行计划,在你开发Node应用、Cli工具或着有复杂的多条script需要执行的时候会很有帮助,同样也是在掘金学到的知识再分享一下?。

?有什么用?

  1. 简化脚本:

使用前: npm run clean && npm run build:css && npm run build:js && npm run build:html

使用后: npm-run-all clean build:*

  1. 跨平台:

主要是因为Windows用户通常使用的cmd.exe不支持&来拼接多条命令,但用户量又大。

?怎么安装?

Node版本>=4均可

命令:

npm install npm-run-all --save-dev
yarn add npm-run-all --dev

?怎么使用?

具体案例可参考文末整理的思维导图或项目的readme文件

  1. 定制复杂计划:npm-run-all
  2. 定制串行计划: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:**
  1. 定制并行计划: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
  1. 在NodeJS里面使用

综上所述的出的结论:

  1. 缺点1:脚本冗余;
  2. 缺点2:跨平台能力差。

命令支持:

npm-run-all

run-s:串行执行示例:

{
  "scripts": {
      "clean": "rimraf dist",
      "lint":  "eslint src",
      "build": "babel src -o lib"
  }
}
  1. npm run 执行:npm run clean && npm run lint && npm run build
  2. run-s执行:run-s clean lint build

run-p:并行执行示例:

{
  "scripts": {
      "clean": "rimraf dist",
      "lint":  "eslint src",
      "build": "babel src -o lib"
  }
}
  1. npm run 执行:npm run lint & npm run build
  2. run-p执行:run-p lint build
  3. 提示:
    1. 代码非正常退出其他脚本将终止进程;
    2. & 操作符在windows系统的cmd.exe不被支持。

思维脑图:https://www.processon.com/view/link/61b453ac5653bb1c942bb3c3