Trung BìnhGit iconGit

Setup pre-commit hook với Husky + lint-staged: tại sao chỉ lint files đang staged thay vì cả project?

Vấn đề nếu lint cả project trên mỗi commit:
- Project lớn → eslint . mất 30-60 giây → developers tắt hooks
- Không liên quan: bạn sửa 1 file nhưng phải đợi 500 files khác lint

lint-staged giải pháp: chỉ chạy linter trên files đang trong git staging area.

Setup:

bash
npm install --save-dev husky lint-staged
npx husky init

package.json:

json
{
  "lint-staged": {
    "*.{ts,tsx}": [
      "eslint --fix",
      "prettier --write"
    ],
    "*.{css,scss}": ["prettier --write"],
    "*.{json,md}": ["prettier --write"]
  }
}

.husky/pre-commit:

bash
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"
npx lint-staged

Kết quả: chỉ 2-3 files được lint → hook chạy trong <3 giây → developers không bỏ hook.

Lưu ý quan trọng về type check trong lint-staged:
tsc --noEmit luôn chạy TOÀN BỘ project typecheck — TypeScript cần full project graph để type-check chính xác, không thể chạy per-file. Nên đặt tsc trong CI thay vì lint-staged, hoặc chấp nhận chi phí full-project check mỗi commit.

Lưu ý: --fix auto-fix và re-stage files đã fix — không cần commit lại. Nhưng nếu auto-fix thay đổi logic → developer phải review.

Xem toàn bộ Git cùng filter theo level & chủ đề con.

Mở danh sách Git