# 九.node.js 脚本
# 1. 安装 shelljs 依赖
使用如下命令安装 shelljs 到项目依赖中:
npm i shelljs -D
# npm install shelljs --save-dev
# yarn add shelljs -D
1
2
3
2
3
此外,我们计划使用 chalk (opens new window) 来给输出加点颜色,让脚本变的更有趣,同样安装到 devDependencies 里面:
npm i chalk -D
# npm install chalk --save-dev
# yarn add chalk -D
1
2
3
2
3
# 2. 创建 Node.js 脚本
touch scripts/cover.js
1
# 3. 用 Node.js 实现同等功能
shelljs 为我们提供了各种常见命令的跨平台支持,比如 cp、mkdir、rm、cd 等命令,此外,理论上你可以在 Node.js 脚本中使用任何 npmjs.com (opens new window) 上能找到的包。清理归档目录、运行测试、归档并预览覆盖率报告的完整 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');
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
关于改动的几点说明:
- 简单的文件系统操作,建议直接使用 shelljs 提供的 cp、rm 等替换;
- 部分稍复杂的命令,比如 nyc 可以使用 exec 来执行,也可以使用 istanbul 包来完成;
- 在 exec 中也可以大胆的使用 npm script 运行时的环境变量,比如
$npm_package_version
;
# 4. 让 package.json 指向新脚本
准备好 Node.js 脚本之后,我们需要修改 package.json 里面的命令,使其运行该脚本:
"scripts": {
"test": "cross-env NODE_ENV=test mocha tests/",
- "cover": "scripty",
+ "cover": "node scripts/cover.js",
"cover:open": "scripty"
},
1
2
3
4
5
6
7
2
3
4
5
6
7
# 5. 测试 cover 命名
重新运行 npm run cover 命令,不出意外的话,基本功能是正常的,除了我们新加的绿色输出,如下图: