npm script 钩子的使用

本文已同步在个人博客: ruizhengyun.cn/blog/post/e…javascript

钩子,命令的执行增长相似于生命周期的一种机制。本章节主要说下 prepost 钩子脚本。其做用或特性体如今一些操做前作检查、一些操做后作清理等场景。css

举例子

lint:js 来讲,运行 npm run lint:js 分 3 个阶段html

  • 检查是否有 prelint:js 命令,有执行;
  • 检查是否有 lint:js 命令,有执行,没有报错;
  • 检查是否有 postlint:js 命令,有执行;

新增 prelint:js

"scripts": {
    ...,
    "prelint:js": "# 检查 .js 前先自动检查 .css \n npm run lint:css & wait",
    "lint:js": "# 检查 .js 代码编程风格 \n eslint ./src/**/*.js",
    ...
}
复制代码

当运行 npm run lint:js 的时候,先回自动执行 prelint:js 里面的 npm run lint:css (并行),输出如图前端

use-hooks-pre

再探 postlint:js

"scripts": {
    ...,
    "prelint:js": "# 检查 .js 前先自动检查 .css \n npm run lint:css & wait",
    "lint:js": "# 检查 .js 代码编程风格 \n eslint ./src/**/*.js",
    "postlint:js": "# 回调 \n rm -rf aaa.js",
    ...
}
复制代码

新增测试覆盖率

本章不是说测试,只是显示 npm script 在测试覆盖率这块的使用场景。java

实现流程:

  • 增长覆盖率收集的命令;
  • 收集覆盖率;
  • 自动打开 html 显示覆盖率报告;

具体步骤

  • 新建 tests 文件夹
  • 新增 add.jsadd.test.js
  • 引入覆盖率收集工具 nyc,是覆盖率工具 istanbul 的命令行版本;
  • 引入一个包 open-cli 打开任意工具 open 的命令版本(打开 html 文件的工具),做者是 sindresorhus,一位前端社区很是高产的工程师。

准备工做

1.add.jsadd.test.jsgit

// add.js
const add = (a, b) => {
    return a + b;
}

module.exports = add;
复制代码
// add.test.js
var add = require('./add.js');
var expect = require('chai').expect;

describe('加法函数的测试', function() {
  it('1 加 1 应该等于 2', function() {
    expect(add(1, 1)).to.be.equal(2);
  });
});
复制代码

2.引入依赖包github

npm i -D nyc open-cli
复制代码

3.脚本编写npm

// package.json
{
    "scripts": {
        "lint-cx:all": "npm-run-all lint:*",
        "lint-cx": "npm run lint:js && npm run lint:jsx && npm run lint:css && npm run lint:json && npm run lint:markdown",
        "lint-bx:all": "# 并行检查全部代码编程风格 \n npm-run-all --parallel lint:*",
        "lint-bx": "npm run lint:js & npm run lint:jsx & npm run lint:css & npm run lint:json & npm run lint:markdown & wait",
        "lint:js": "# 检查 .js 代码编程风格 \n eslint ./src/**/*.js & wait",
        "lint-fix:js": "npm run lint:js -- --fix",
        "lint:jsx": "eslint ./src/**/*.jsx & wait",
        "lint:css": "stylelint ./src/**/*.{html,css,less,scss} & wait",
        "lint-fix:css": "npm run lint:css -- --fix",
        "lint:json": "jsonlint --quiet ./src/**/*.json",
        "lint:markdown": "markdownlint --config .markdownlint.json ./src/**/*.md",
        "mocha": "mocha tests/",
        "test": "# 运行全部代码检查和单元测试 \n npm-run-all --parallel lint:* mocha",
        "precover": "rm -rf coverage",
        "cover": "nyc --reporter=html npm test",
        "postcover": "rm -rf .nyc_output && open coverage/index.html"
    },
    "nyc": {
        "exclude": [
            "**/*.spec.js",
            ".*.js"
        ] 
    }
}
复制代码

4.说明下编程

  • precover,收集覆盖率以前把以前的覆盖率报告目录清理掉;
  • cover,直接调用 nyc,让其生成 html 格式的覆盖率报告;
  • postcover,清理掉临时文件,而且在浏览器中预览覆盖率报告;

5.执行 npm run coverjson

覆盖率收集

覆盖率收集

覆盖率查看

覆盖率查看

小结

目前为止,前端工做流中含有

  • 代码检查
  • 测试运行
  • 覆盖率收集和覆盖率查看

那是否是能够改进下咱们本身的工做流呢?

你能够...

上一篇: npm script 参数的使用

下一篇:npm script 环境变量的使用

目录:npm script 小书

相关文章
相关标签/搜索