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

发布于:2025-08-18 ⋅ 阅读:(19) ⋅ 点赞:(0)

什么是 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

npm install --save-dev npm-run-all2
# 或者
yarn add --dev npm-run-all2

基本用法

顺序运行脚本

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

{
  "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)并行运行脚本:

{
  "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 将同时运行所有测试脚本。

高级特性

带前缀的脚本名称

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

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

组合使用

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

{
  "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"
  }
}

参数传递

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

{
  "scripts": {
    "lint": "run-s lint:*",
    "lint:js": "eslint",
    "lint:css": "stylelint"
  }
}

然后运行:

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 是一个值得考虑的选择。

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


网站公告

今日签到

点亮在社区的每一天
去签到