公司项目开发中,都会有不少种规范,代码规范,提交规范等等,目的就是为了使团队代码风格统一,便于阅读,便于理解。css
经过使用以上工具,项目将会具有校验提交信息是否规范,提交前格式化代码,lint代码等功能。html
如不少其余版本控制系统同样,git
也具备在特定时间执行特定动做的脚本功能。husky
其实就是一个为 git 客户端增长 hook 的工具。它提供了不少git hooks
(如commit
, push
, receive
等),咱们能够很方便在这些钩子中检测提交信息是否规范,运行测试用例,检测代码等等。vue
commitlint 能够校验提交信息是否规范,提交格式以下:webpack
git commit -m <type>: <description>
复制代码
其中type
能够是如下值:git
build
:主要目的是修改项目构建系统(例如 glup,webpack,rollup 的配置等)的提交ci
:主要目的是修改项目继续集成流程(例如 Travis,Jenkins,GitLab CI,Circle等)的提交docs
:文档更新feat
:新增功能fix
:bug 修复perf
:性能优化refactor
:重构代码(既没有新增功能,也没有修复 bug)style
:不影响程序逻辑的代码修改(修改空白字符,补全缺失的分号等)test
:新增测试用例或是更新现有测试revert
:回滚某个更早以前的提交chore
:不属于以上类型的其余类型(平常事务)例如:github
git commit -m "fix: 修复什么bug"
复制代码
能够运行相关lint插件进行代码检测。web
能够对代码进行格式化,保证代码统一格式。vue-cli
husky
yarn add husky -D
复制代码
.husky
的目录。yarn husky install
复制代码
{
"scripts": {
"postinstall": "husky install"
}
}
复制代码
注意:若是是npm
安装,能够参照这里npm
commitlint
yarn add @commitlint/cli @commitlint/config-conventional -D
复制代码
echo "module.exports = {extends: ['@commitlint/config-conventional']}" > commitlint.config.js
复制代码
或者在根目录新建这个commitlint.config.js
文件,而后输入下面内容:json
module.exports = {extends: ['@commitlint/config-conventional']}
复制代码
commit-msg
钩子yarn husky add .husky/commit-msg 'yarn commitlint --edit "$1"'
复制代码
执行完上述命令之后,.husky
下面会有commit-msg
的文件。 至此,项目能够校验提交信息,是否符合规范,有想尝试的能够试下。
#!/bin/sh
command_exists () {
command -v "$1" >/dev/null 2>&1
}
# Windows 10, Git Bash and Yarn workaround
if command_exists winpty && test -t 1; then
exec < /dev/tty
fi
复制代码
而后在对应的勾子文件中,增长一行 . "$(dirname "$0")/common.sh"
代码
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
. "$(dirname "$0")/common.sh"
yarn …
复制代码
注意:全部*.sh
文件的第一行必须是#!/bin/sh
,不然会出现报错:error: cannot spawn git: No such file or directory
lint-staged
yarn add lint-staged -D
复制代码
.lintstagedrc
配置文件{
"./src/**/*.{js,jsx,ts,tsx,vue,less,sass,scss,css.json}": ["prettier --write"],
}
复制代码
prettier
yarn add prettier -D
复制代码
.prettierrc.js
文件// 详见https://prettier.io/docs/en/options.html
module.exports = {
printWidth: 80, // 每行的长度
tabWidth: 2, // 缩进的空格数
useTabs: false, // 用tabs而不是空格缩进
semi: true, // 每一个语句末尾是否加分号,false只有在编译报错时才加
singleQuote: false, // 使用单引号代替双引号,jsx引号规则将会忽略此配置。
quoteProps: "as-needed", //
jsxSingleQuote: false, // 在jsx中使用单引号代替双引号
trailingComma: "es5", // 是否有末尾的逗号,例如数组或对象的最后一项。/es5/none/all
bracketSpacing: false, // 在对象字面量{}的语法中打印空格
jsxBracketSameLine: false, // 开始标签的>是否和以前内容在同一行
arrowParens: "always", // 箭头函数的参数是否加括号 /always/avoid
rangeStart: 0, // 须要格式化的开始位置
rangeEnd: Infinity, // 须要格式化的结束位置
};
复制代码
pre commit
钩子.husky
目录下面有个文件pre-commit
yarn husky add .husky/pre-commit 'yarn lint-staged --allow-empty "$1" && yarn lint'
复制代码
项目若是使用vue-cli
建立的,package.json
的scripts
中会有lint: vue-cli-service lint
。若是想执行其余lint插件,能够将上面的yarn lint
修改。
注意:若是commit
出现stdin is not a tty
的报错。参考
至此。完结。
若是不想加入 配置husky
中的第3步,能够删除.husky
下的.gitignore
文件。
若是不想安装lint-staged
,能够将文件pre-commit
里的命令改成:
yran prettier "./src/**/*.{js,jsx,ts,tsx,vue,less,sass,scss,css.json}" --write && yarn lint
复制代码