npm script 多命令的运行

7,294 阅读2分钟

本文已同步在我的博客: ruizhengyun.cn/blog/post/c…

一个项目难免会有多个 npm script, 如何将多个命令串行(就是多个脚本通同步执行),如何并行(提高速度,互不阻塞)。

为何有多个命令

一般来说,前端项目包括 js、less、css、scss、json、markdown 等格式的文件,为了保障代码的质量(规避语法错误和保持一致的编码风格),就需要添加检查。在团队中更加提现其价值。

常用检查

  • eslint, 可定制的 js 代码检查
  • stylelint, 可定制的样式文件检查,支持 css、less、scss;
  • jsonlint, json 文件语法检查,踩过坑的同学会清楚,json 文件语法错误会知道导致各种失败;
  • markdownlint-cli, Markdown 文件最佳实践检查,个人偏好;

有人问,html 代码怎么不列出来呢?其实我也想,只是工具支持薄弱,就...

"scripts": {
    "lint:js": "eslint ./src/**/*.js",
    "lint:jsx": "eslint ./src/**/*.jsx",
    "lint:css": "stylelint ./src/**/*.less",
    "lint:json": "jsonlint --quiet ./src/**/*.json",
    "lint:markdown": "markdownlint --config .markdownlint.json ./src/**/*.md"
},
"devDependencies": {
    "eslint": "^5.16.0",
    "eslint-config-airbnb": "^17.1.0",
    "eslint-plugin-import": "^2.17.3",
    "eslint-plugin-jsx-a11y": "^6.2.1",
    "eslint-plugin-react": "^7.13.0",
    "jsonlint": "^1.6.3",
    "markdownlint-cli": "^0.16.0",
    "stylelint": "^10.0.1",
    "stylelint-config-standard": "^18.3.0"
},
"dependencies": {
    "react": "^16.8.6",
    "react-dom": "^16.8.6"
}

串行

实现方式很简单,用 && 符号按顺序把命令串联起来。

"scripts": {
    ...,
    "lint:cx": "npm run lint:js && npm run lint:jsx && npm run lint:css && npm run lint:json && npm run lint:markdown"
}

注: 串行命令执行过程中,如果前面的命令失败,后面命令会全部终止。示例很简单,自己试下就好。

并行

其实也很简单,用一个 & 连接多个命令。

"scripts": {
    ...,
    "lint:bx": "npm run lint:js & npm run lint:jsx & npm run lint:css & npm run lint:json & npm run lint:markdown"
}

注: 并行命令,为了稳定复现一些错误,可在命令最后加上 & wait。另外,加上 & wait 的好处还有,如果我们在子命令启动长时间运行的进程,可用 ctrl + c 来结束进程。

更好的管理

并行或串行的命令中,每添加一条就要加上 npm run xxx,重复部分显得啰嗦臃肿,可以用 npm i npm-run-all 来实现同样的功能。

"scripts": {
    ...,
    "lint:cx-all": "npm-run-all lint:js lint:jsx lint:css lint:json lint:markdown"
}

npm-run-all 还支持通配符,进一步优化

"scripts": {
    ...,
    "lint-cx-all": "npm-run-all lint:*"
}

上面只是用 npm-run-all 实现了串行,那并行是怎样的呢?

"scripts": {
    ...,
    "lint:bx-all": "npm-run-all --parallel lint:*"
}

注 这次我们没有在并行的后面加上 & wait,或许你猜到了,npm-run-all 帮我们做了(做好事不留名)

补充 parallel,[ˈpærəlel],平行的;极相似的;同时发生的;相应的;对应的;并行的 更多关于 npm-run-all 可看文档

你可以...

上一篇:npm script 一见钟情

下一篇:npm script 参数的使用

目录:npm script 小书