npm学习 02多个npm script串行与并行

本文探讨了npm在package.json中如何配置串行和并行执行脚本。串行执行时,如果前一个命令失败,后续命令将全部停止。并行执行则类似于JavaScript的异步请求,npm通过&符号触发多条命令但不处理结果。推荐使用npm-run-all工具,它能更方便地管理和控制串行与并行任务,并且在并行执行时,配合wait可以方便地结束后台进程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package.json

{
  "name": "npmlearn",
  "version": "0.1.0",
  "description": "no",
  "main": "index.js",
  "scripts": {
    "lint:js": "eslint *.js",
    "lint:css": "stylelint *.less",
    "lint:json": "jsonlint --quiet *.json",
    "lint:markdown": "markdownlint --config .markdownlint.json *.md",
    "test": "mocha tests/"
  },
  "keywords": [],
  "author": "linjh <875952924@qq.com> (http://github.com/lllanlll)",
  "license": "MIT",
  "devDependencies": {
    "chai": "^4.1.2",
    "eslint": "^6.5.1",
    "jsonlint": "^1.6.2",
    "markdownlint-cli": "^0.5.0",
    "mocha": "^4.0.1",
    "npm-run-all": "^4.1.5",
    "stylelint": "^8.2.0",
    "stylelint-config-standard": "^17.0.0"
  }
}

1.串行:串行执行的时候如果前序命令失败(通常进程退出码非0),后续全部命令都会终止

1.“test”: “npm run lint:js && npm run lint:css && npm run lint:json && npm run lint:markdown && mocha tests/” 使用&&连接各命令

2.并行: npm 内置支持的多条命令并行跟 js 里面同时发起多个异步请求非常类似,它只负责触发多条命令,而不管结果的收集

1. “test”: “npm run lint:js & npm run lint:css & npm run lint:json & npm run lint:markdown & mocha tests/” 使用&连接各命令 若在后面加上 & wait
加上 wait 的额外好处是,如果我们在任何子命令中启动了长时间运行的进程,比如启用了 mocha 的 --watch 配置,可以使用 ctrl + c 来结束进程,如果没加的话,你就没办法直接结束启动到后台的进程。

推荐:使用npm-run-all

添加依赖:

npm i npm-run-all -D
//串行
  "mocha": "mocha tests/",
  "test": "npm-run-all lint:js lint:css lint:json lint:markdown mocha"
  //还可以使用通配符选择:
  //"test": "npm-run-all lint:* mocha"
//并行
   "test": "npm-run-all --parallel lint:* mocha"
   //不用 & wait 因为npm-run-all默认执行了
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值