完结,✿✿ヽ(°▽°)ノ✿ 撒花🎉🎉🎉🎉。二十周,终于学完了前端训练营了,中间经历了一个春节,叠加一些事情,慢了点完成学习任务。整体感觉,这是个很不错的训练营,有需要的同学可以一试,不过确实需要花不少时间,师傅领入门,修行始终靠自己。
这周学习了最后的内容,发布前的一些检查(也可以说是持续集成的一部分)。
检查时机 -- Git Hooks
在当前仓库里.git/hooks文件夹下有很多 git hooks 例子
课程里,主要用到pre-commit这个 hooks。在git commit前利用这个hooks进行检查
 ## 在.git/hooks文件夹下创建文件pre-committouch pre-commit## 为pre-commit添加执行权限,不然不能执行pre-commit代码chmod +x pre-commit
       复制代码
 
以下是pre-commit内代码:
 #!/usr/bin/env nodelet process = require("process");console.log("Hello, hooks!")
// 退出命令process.exitCode = 1;
       复制代码
 这是pre-commit基本用法,课程里采用nodejs作为脚本引擎来执行
代码检查 -- ESLint
ESLint是JavaScript的一款轻量级代码风格检查工具
配置 ESLint 环境
 ## 创建一个npm环境mkdir eslint-democd eslint-demonpm init## 安装ESLintnpm install --save-dev eslint## 配置ESLint,采用默认配置就行了npx eslint --init## 对index.js进行代码检查npx eslint index.js
       复制代码
 
以下是pre-commit内代码,利用ESLintAPI 和git hooks在git commit前进行代码检查
 #!/usr/bin/env nodelet process = require("process");let child_process = require("child_process");const { ESLint } = require("eslint");
//  用于执行git命令function exec(name) {    return new Promise(function(resolve) {        child_process.exec(name, resolve);    })}
(async function main() {  // 1. Create an instance with the `fix` option.  const eslint = new ESLint({ fix: false });
  // 2. Lint files. This doesn't modify target files.  await exec("git stash push -k"); // 解决边界问题,先用git stash保存当前修改  const results = await eslint.lintFiles(["index.js"]);  await exec("git stash pop"); // 检查完后恢复之前的修改状态
  // 4. Format the results.  const formatter = await eslint.loadFormatter("stylish");  const resultText = formatter.format(results);
  // 5. Output it.  console.log(resultText);
  // 对结果进行检查,有错误就终止操作  for (const result of results) {      if (result.errorCount) {          process.exitCode = 1;      }  }  })().catch((error) => {  process.exitCode = 1;  console.error(error);});
       复制代码
 
ESLint只会对文件当前内容进行检查,在暂存区的文件不会被检查,为了配合git的几个文件修改状态,所以需要通过git stash对当前文件修改进行保存,在检查后再恢复到当前状态,保障了暂存区的文件能通过ESLint的检查。
发布前检查 -- Puppeteer
需要安装 Chrome 浏览器,然后利用 Chrome 的 Headless 模式进行 DOM 检查
 ## 命令行配置chrome快捷方式alias chrome="/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome"## 无头浏览器chrome --headless## 打印about:blank 的DOM树chrome --headless --dump-dom about:blank
       复制代码
 
Puppeteer是 Chrome 推出的一个Node库,通过Puppeteer的 API 进行 DOM 检查,Puppeteer默认是 Headless 模式
Puppeteer的例子代码如下:
 const puppeteer = require('puppeteer');
(async () => {  const browser = await puppeteer.launch();  const page = await browser.newPage();  // 这里用之前component作为检查对象  await page.goto('http://localhost:8080/main.html');  const imgs = await page.$$('a');   console.log(imgs);})();
       复制代码
 本周学习内容
发布前检查
Git Hooks 用法
ESLint 及其 API 用法
使用无头浏览器检查 DOM(Puppeteer)
参考资料
Git - Git Hooks
Getting Started with ESLint - ESLint - Pluggable JavaScript linter
Node.js API - ESLint - Pluggable JavaScript linter
Getting Started with Headless Chrome
puppeteer/api.md at v5.3.0 · puppeteer/puppeteer · GitHub
评论