You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
!/usr/bin/env bash
# get files to be linted
FILES=$(git diff --cached --name-only | grep -E '^src|^test/unit/specs|^test/e2e')# lint them if anyif [[ $FILES ]];then
./node_modules/.bin/eslint $FILESfi
constchalk=require('chalk')constmsgPath=process.env.GIT_PARAMSconstmsg=require('fs').readFileSync(msgPath,'utf-8').trim()constcommitRE=/^(revert:)?(feat|fix|polish|docs|style|refactor|perf|test|workflow|ci|chore|types|build)(\(.+\))?:.{1,50}/if(!commitRE.test(msg)){console.log()console.error(` ${chalk.bgRed.white(' ERROR ')}${chalk.red(`invalid commit message format.`)}\n\n`+chalk.red(` Proper commit message format is required for automated changelog generation. Examples:\n\n`)+` ${chalk.green(`feat(compiler): add 'comments' option`)}\n`+` ${chalk.green(`fix(v-model): handle events on blur (close #28)`)}\n\n`+chalk.red(` See .github/COMMIT_CONVENTION.md for more details.\n`)+chalk.red(` You can also use ${chalk.cyan(`npm run commit`)} to interactively generate a commit message.\n`))process.exit(1)}
在看vue源码时,不免修改代码,就会触发里面配置好的钩子函数。于是,仔细研究了一下vue配置方法,可以发现配置非常简单。
git 钩子文档上介绍非常详细,
git init
后,在.git/hooks
文件中,有一些.simple
结尾的钩子示例脚本,如果想启用对应的钩子函数,只需手动删除后缀。所以,列出两种配置方法:1. 手动修改钩子文件
按照文档上,配置钩子脚本,修改hooks中文件名对应的钩子文件,启用钩子。使用shell脚本检查,可以参考vue1.x 里面如何使用
文件名是
pre-commit
,在commit 之前启用的钩子函数, 利用git diff
查看当前有哪些文件修改过,只对指定文件夹中修改的文件使用eslint进行代码检查,渐进式对整个项目实现代码规范。脚本写好后,不用每次都手动复制到
.git/hooks
目录下,只需对当前文件创建软连接,到指定目录,在package.json中配置脚本命令,在项目初始化后, 执行
npm run install-hook
,很方便地配置好了pre-commit 钩子2. 利用yorkie or husky + lint-staged 构建钩子
在 vue最新的版本中,已经使用尤大改写的youkie, youkie实际是fork husky,然后做了一些定制化的改动, 使得钩子能从package.json的 "gitHooks"属性中读取,
使用方法跟husky 类似,可以查看husky 文档,介绍非常详细。
安装完成后,可以发现已经改写了hooks 目录中的文件,只需在package.json 中配置对应钩子要执行的脚本。
husky 配置:
回头看看,vue中如何配置
前面提到,利用
git diff
,只lint当前改动的文件,lint-staged就非常准确的解决了这一问题,从这个包名,就可以看出,Run linters on git staged files
,只针对改动的文件进行处理。结合husky一起使用,安装依赖:
修改package.json 文件
使用了eslint,需要配置.eslintrc, lint-staged还有一个好处,可以在lint后,更加灵活,执行其他脚本,尝试进行修改错误,比如
eslint --fix
检查后并修复错误。上面列出的vue 文件使用了类似的配置,另外增加了 commit-msg 钩子,对提交说明进行检查,在 scripts/verify-commit-msg.js文件中可以找到检查脚本,
利用process.env.GIT_PARAMS 找到目录,读取msg 说明,进行检查。
使用 husky 要注意,对应属性名已经改为HUSKY_GIT_PARAMS , 而不是原始的 GIT_PARAMS 环境变量。
The text was updated successfully, but these errors were encountered: