項目(vue3)中添加husky、eslint、prettier , 自動格式化代碼, 保姆級教學。
日常開發中,項目基本上都是由多個人進行開發和維護,每個人的代碼書寫習慣和風格又不盡相同,commit log也是亂七八糟,為以后的開發和維護增添了很多困難。所以,規范和約束在多人協作下,就顯得尤為重要。
首先安裝代碼檢查工具
- Eslint
npm i eslint -D
Eslint 安裝成功后,在項目根目錄下執行
npx eslint --init
然后按照終端操作的提示完成一系列設置來創建配置文件。你可以按照下圖所示的選擇來始化 ESLint
這樣的設置比較松散,可以在eslintrc.json 中設置規則
比如行尾不寫分號
"rules": {
"semi": ["warn","never"]
}
然后我們執行
npx eslint src
就可以看到當前項目中哪些不符合規范
上面每次都需要執行npx eslint xxx才能校驗,很麻煩。有沒有辦法在代碼保存的時候自動執行Eslint,只需要安裝Eslint插件即可:
VSCode中插件市場安裝Eslint
然后設置中添加
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true
}
更多規則請看這里
在vue3中可能會出現的錯誤:
- 錯誤1
Parsing error: '>' expected.eslint
需要在.eslintrc.json中指定解析器
"parser": "vue-eslint-parser"
- 錯誤2
在vue3.2中不需要申明 emit和props
error ‘defineProps’ is not defined no-undef
解決:
"env": {
"vue/setup-compiler-macros": true
},
- 錯誤3
如果有jest,同樣需要做相應的配置。
"env": {
"jest": true
},
這樣,Eslint這塊算是完成了,接下來我們添加prettier
npm i prettier eslint-config-prettier eslint-plugin-prettier -D
在根目錄創建.prettierrc
{
"semi": false,
"tabWidth": 2,
"trailingComma": "none",
"singleQuote": true,
"arrowParens": "avoid"
}
同樣vscode中安裝prettier
設置中搜索Formar On Save 並勾選
設置中添加
"[javascript]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
}
在.eslintrc 中,extend中添加 "prettier" 解決 eslint 和 prettier 的沖突
更多規則請看這里
設置完需要重啟,否則不會生效
代碼提交規范 husky
- 這里用的husky是7.0.4版本的,老版本可自行百度
簡單的舉一些常見的githooks例子
Git Hook | 執行時機 | 說明 |
---|---|---|
pre-commit | git commit執行前 | 可以用git commit --no-verify繞過 |
commit-msg | git commit執行前 | 可以用git commit --no-verify繞過 |
詳細的hooks介紹可以點擊這里
首先安裝
npm install -D husky
初始化husky
npx husky install .husky
添加一個commit msg鈎子
npx husky add .husky/commit-msg "node scripts/verifyCommit.js"
創建verifyCommit.js
添加代碼
這段代碼邏輯是,找到文件並讀取了commit的提交信息,然后使用正則去校驗提交信息的格式,如果commit的信息不符合要求,會直接報錯並且終止代碼的提交。
const msg = require('fs')
.readFileSync('.git/COMMIT_EDITMSG', 'utf-8')
.trim()
const commitRE = /^(revert: )?(feat|fix|docs|dx|style|refactor|perf|test|workflow|build|ci|chore|types|wip|release)(\(.+\))?: .{1,50}/
const mergeRe = /^(Merge pull request|Merge branch)/
if (!commitRE.test(msg)) {
if(!mergeRe.test(msg)){
console.log('git commit信息校驗不通過')
console.error(`git commit的信息格式不對, 需要使用 title(scope): desc的格式
比如 fix: xxbug
feat(test): add new
具體校驗邏輯看 scripts/verifyCommit.js
`)
process.exit(1)
}
}else{
console.log('git commit信息校驗通過')
}
在commit-msg執行的時候我們還可以用代碼執行之前的鈎子,pre-commit,去執行ESLint代碼格式,
這樣我們在執行git commit的時候,首先會進行ESLint校驗,然后在執行commit的log信息格式檢查,全部通過后代碼才能提交至Git。
npx husky add .husky/pre-commit "npm run lint"
package.json 中創建
"lint": "eslint --fix --ext .js,vue src/"
commit msg參考
feat: 新功能
fix: 修改 bug
docs: 文檔
perf: 性能相關
refactor: 代碼重構(就是不影響使用,內部結構的調整)
test: 測試用例
style: 樣式修改
workflow: 工作流
build: 項目打包構建相關的配置修改
ci: 持續集成相關
revert: 恢復上一次提交(回滾)
wip: work in progress 工作中 還沒完成
chore: 其他修改(不在上述類型中的修改)
release: 發版
deps: 依賴相關的修改
總結
我們通過在項目中添加eslint與prettier和相對應的規則來約束代碼,使用husky在代碼提交的時候檢測代碼和約束提交log。