使用 npm-run-all2 简化你的 npm 脚本工作流

什么是 npm-run-all2?

npm-run-all2 是 npm-run-all 的一个维护分支,它是一个 CLI 工具,用于并行或顺序运行多个 npm 脚本。这个工具特别适合那些需要执行多个相关任务(如构建步骤、测试套件等)的 Node.js 项目。

为什么选择 npm-run-all2?

原始的 npm-run-all 包已经有一段时间没有积极维护了,npm-run-all2 作为社区维护的分支,解决了以下问题:

  • 保持与最新 Node.js 版本的兼容性
  • 修复了原始包中的一些长期存在的 bug
  • 提供了更好的 TypeScript 支持
  • 继续接受社区贡献

安装 npm-run-all2

bash 复制代码
npm install --save-dev npm-run-all2
# 或者
yarn add --dev npm-run-all2

基本用法

顺序运行脚本

使用 run-s 命令(或 npm-run-all2 -s)按顺序运行脚本:

json 复制代码
{
  "scripts": {
    "build": "run-s clean lint compile",
    "clean": "rimraf dist",
    "lint": "eslint src",
    "compile": "babel src -d dist"
  }
}

运行 npm run build 将依次执行 clean、lint 和 compile 脚本。

并行运行脚本

使用 run-p 命令(或 npm-run-all2 -p)并行运行脚本:

json 复制代码
{
  "scripts": {
    "test": "run-p test:*",
    "test:unit": "jest --config jest.unit.config.js",
    "test:integration": "jest --config jest.integration.config.js",
    "test:e2e": "cypress run"
  }
}

运行 npm run test 将同时运行所有测试脚本。

高级特性

带前缀的脚本名称

你可以使用通配符来匹配多个脚本:

json 复制代码
{
  "scripts": {
    "start": "run-p dev:*",
    "dev:server": "nodemon server.js",
    "dev:client": "webpack-dev-server",
    "dev:logger": "node logger.js"
  }
}

组合使用

你可以混合使用顺序和并行执行:

json 复制代码
{
  "scripts": {
    "deploy": "run-s build test deploy:now",
    "build": "run-p build:*",
    "build:js": "webpack",
    "build:css": "postcss src -d dist",
    "test": "jest",
    "deploy:now": "now --prod"
  }
}

参数传递

你可以向子脚本传递参数:

json 复制代码
{
  "scripts": {
    "lint": "run-s lint:*",
    "lint:js": "eslint",
    "lint:css": "stylelint"
  }
}

然后运行:

bash 复制代码
npm run lint -- --fix

这将把 --fix 参数传递给所有 lint 子脚本。

与原始 npm-run-all 的区别

  1. 更好的错误处理
  2. 改进的 Windows 支持
  3. 更新的依赖项
  4. 更清晰的调试输出

迁移指南

如果你正在使用原始的 npm-run-all,迁移到 npm-run-all2 非常简单:

  1. 卸载原始包:npm uninstall npm-run-all
  2. 安装新包:npm install --save-dev npm-run-all2
  3. 更新 package.json 中的脚本(如果需要)

大多数情况下,你甚至不需要更改任何脚本,因为 API 是完全兼容的。

结论

npm-run-all2 是一个强大的工具,可以帮助你简化复杂的 npm 脚本工作流。通过并行或顺序运行多个脚本,你可以创建更高效、更易维护的构建流程。如果你正在寻找原始 npm-run-all 包的替代品,npm-run-all2 是一个值得考虑的选择。

尝试在你的下一个项目中使用它,看看它如何简化你的开发工作流程!

相关推荐
irving同学462389 分钟前
TypeORM 列装饰器完整总结
前端·后端·nestjs
彭于晏爱编程12 分钟前
你真的了解 Map、Set 嘛
前端
崔璨16 分钟前
详解Vue3的响应式系统
前端·vue.js
摸鱼的鱼lv16 分钟前
🔥 Vue.js组件通信全攻略:从父子传值到全局状态管理,一篇搞定所有场景!🚀
前端·vue.js
IT_陈寒27 分钟前
Java性能优化:10个让你的Spring Boot应用提速300%的隐藏技巧
前端·人工智能·后端
whysqwhw1 小时前
Hippy 跨平台框架扩展原生自定义组件的完整实现方案对比
前端
dasseinzumtode1 小时前
nestJS 使用ExcelJS 实现数据的excel导出功能
前端·后端·node.js
子兮曰1 小时前
🔥C盘告急!WSL磁盘暴增?三招秒清20GB+空间
前端·windows·docker
Jinuss1 小时前
Vue3源码reactivity响应式篇之EffectScope
前端·vue3
stoneship1 小时前
网页截图API-Npm工具包分享
前端