"เคยไหม... commit โค้ดไปโดยลืมลบ console.log()
หรือ push โค้ดที่ไม่ผ่าน lint ไปยัง production
ถ้าเคย — คุณต้องรู้จัก Husky แล้วล่ะ!"
Husky เป็นเครื่องมือที่ช่วยให้เราใช้งาน Git Hooks ได้ง่ายขึ้น โดย Git Hooks คือสคริปต์ที่ Git เรียกใช้ในช่วงเวลาต่าง ๆ เช่น pre-commit, pre-push, commit-msg เพื่อให้เราสามารถตรวจสอบ หรือล็อกการกระทำบางอย่างไว้ก่อนจะเกิดขึ้น
ติดตั้งผ่าน npm, yarn, หรือ pnpm ก็ได้ (ในที่นี้ใช้ pnpm เป็นตัวอย่าง)
pnpm add -D husky
npx husky install
เพิ่ม script prepare ใน package.json เพื่อให้ Husky พร้อมทำงานหลังติดตั้ง dependencies:
{
"scripts": {
"prepare": "husky install"
}
}
จากนั้นรัน:
pnpm run prepare
สร้าง pre-commit hook แบบง่าย ๆ
ตัวอย่าง: เช็ก lint ก่อน commit
สร้างคำสั่ง lint ใน package.json
{
"scripts": {
"lint": "eslint . --ext .ts,.tsx"
}
}
สร้างไฟล์ pre-commit ด้วยคำสั่ง Husky:
npx husky add .husky/pre-commit "pnpm run lint"
ตอนนี้ใน .husky/pre-commit จะมี:
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
pnpm run lint
ทุกครั้งที่คุณ git commit, Husky จะเช็ก lint ให้ก่อนอัตโนมัติ
ถ้าโค้ดมี error หรือ warning ที่ตั้งไว้ strict — commit จะถูกบล็อก!
เพิ่มความเทพด้วยหลายคำสั่ง
เราสามารถเช็กหลายอย่างได้พร้อมกัน เช่น:
- เช็ก lint
- Format ด้วย Prettier
- บล็อก console.log ด้วย ESLint rule
npx husky add .husky/pre-commit "pnpm run lint && pnpm run format"
ถ้ามีคำสั่งล้มเหลวเพียงคำสั่งเดียว — commit จะถูกยกเลิก
ตัวอย่าง Prettier Format Script
{
"scripts": {
"format": "prettier --write ."
}
}
เพิ่มการบล็อก console.log() ด้วย ESLint
ติดตั้ง plugin:
pnpm add -D eslint-plugin-no-console
ใน .eslintrc.js:
module.exports = {
plugins: ['no-console'],
rules: {
'no-console': ['error', { allow: ['warn', 'error'] }],
},
}
ทดสอบการทำงาน
ลองเขียนโค้ดที่มี console.log() หรือผิด format
- ใช้ git add .
- ใช้ git commit -m "test commit"
- คุณจะเห็นว่า commit ถูกบล็อก พร้อมแสดง error ที่เกิดขึ้น
ตัวอย่างการใช้ commit-msg (เพิ่มเติม)
อยากให้ commit message เป็นแบบ conventional commits ใช่ไหม?
ติดตั้ง commitlint
pnpm add -D @commitlint/{config-conventional,cli}
สร้าง commitlint.config.js:
module.exports = {
extends: ['@commitlint/config-conventional'],
}
เพิ่ม hook:
npx husky add .husky/commit-msg 'npx --no -- commitlint --edit "$1"'
สรุป
✅ สิ่งที่ได้จาก Husky | 🚫 สิ่งที่ป้องกัน |
---|---|
เพิ่มความมั่นใจให้ทีม | commit โค้ดไม่ผ่าน lint |
ลด bug จาก code style | push โค้ดผิด format |
รองรับ flow แบบทีมใหญ่ | commit message ไม่เป็นมาตรฐาน |
"เขียนโค้ดให้ดีนั้นสำคัญ
แต่ กันไม่ให้โค้ดพัง ตั้งแต่ก่อน commit — สำคัญยิ่งกว่า
และ Husky ก็เป็นผู้ช่วยที่คุณจะหลงรักแน่นอน"
Top comments (0)