0
点赞
收藏
分享

微信扫一扫

npm script工作流(八) node.js 脚本替代复杂的 npm script

月白色的大狒 2021-09-28 阅读 82
技术

Node.js

  • Node.js 本身是跨平台的,用它编写的脚本出现跨平台兼容问题的概率很小。

shelljs

  • 安装
npm i shelljs -D
# npm install shelljs --save-dev
# yarn add shelljs -D

chalk 来给输出加点颜色

npm i chalk -D
# npm install chalk --save-dev
# yarn add chalk -D
  • 创建 Node.js 脚本
touch scripts/cover.js
  • Node.js 实现同等功能
    shelljs 为我们提供了各种常见命令的跨平台支持,比如 cp、mkdir、rm、cd 等命
    Node.js 脚本中使用任何 npmjs.com 上能找到的包。
    清理归档目录、运行测试、归档并预览覆盖率报告的完整 Node.js 代码如下
const { rm, cp, mkdir, exec, echo } = require('shelljs');
const chalk = require('chalk');

console.log(chalk.green('1. remove old coverage reports...'));
rm('-rf', 'coverage');
rm('-rf', '.nyc_output');

console.log(chalk.green('2. run test and collect new coverage...'));
exec('nyc --reporter=html npm run test');

console.log(chalk.green('3. archive coverage report by version...'));
mkdir('-p', 'coverage_archive/$npm_package_version');
cp('-r', 'coverage/*', 'coverage_archive/$npm_package_version');

console.log(chalk.green('4. open coverage report for preview...'));
exec('npm-run-all --parallel cover:serve cover:open');
  • 简单的文件系统操作,建议直接使用 shelljs 提供的 cp、rm 等替换;
  • 部分稍复杂的命令,比如 nyc 可以使用 exec 来执行,也可以使用 istanbul 包来完成;
  • 在 exec 中也可以大胆的使用 npm script 运行时的环境变量,比如 $npm_package_version
  • package.json 指向
   "scripts": {
     "test": "cross-env NODE_ENV=test mocha tests/",
-    "cover": "scripty",
+    "cover": "node scripts/cover.js",
     "cover:open": "scripty"
   }
  • 测试 cover 命名
  • npm run cover
举报

相关推荐

0 条评论