husky & lint-staged
Husky란?
Husky는 Git Hooks를 JavaScript로 쉽게 관리할 수 있게 해주는 npm 패키지이다. Git Hooks는 특정 Git 이벤트(commit, push 등)가 발생할 때 자동으로 실행되는 스크립트로, 코드 품질을 유지하는 데 매우 유용하다. Husky를 사용하면 프로젝트의 모든 개발자가 동일한 Git Hooks를 사용할 수 있도록 설정을 공유할 수 있다.
주요 기능
적용 방법
1. 필요한 패키지 설치
# ESLint, Prettier, Husky 관련 패키지 설치npm i -D @typescript-eslint/eslint-plugin eslint-plugin-prettier @typescript-eslint/parser eslint eslint-config-airbnb eslint-config-airbnb-typescript eslint-config-prettier eslint-plugin-html eslint-plugin-import eslint-plugin-jsx-a11y eslint-plugin-react eslint-plugin-react-hooks prettier husky lint-staged
2. Prettier와 ESLint 설정
3. .gitignore에 .eslintcache 추가
# 기존 .gitignore 내용# ...# ESLint 캐시 파일.eslintcache
ESLint 캐시란?
ESLint 캐시(.eslintcache)는 ESLint가 이전에 검사한 파일의 정보를 저장하는 파일이다. ESLint를 --cache 옵션과 함께 실행하면 생성된다. 이 캐시 파일은 다음과 같은 이유로 중요하다.
.gitignore에 추가해야 하는 이유
ESLint 캐시를 사용하면서 .gitignore에 추가함으로써, 빠른 린팅 성능을 유지하면서도 Git 저장소를 깔끔하게 관리할 수 있다.
4. package.json 설정
{"scripts": {"postinstall": "husky init && echo 'npx lint-staged' > .husky/pre-commit && echo 'npm run lint' > .husky/pre-push","format": "prettier --write --cache .","lint": "eslint --cache ."},"lint-staged": {"*.{ts,tsx,js,jsx}": ["npm run format"]}}
5. Husky 초기화 및 Hook 설정
최신 Husky 버전(v9+)에서는 다음과 같이 설정합니다.
# Husky 초기화npx husky init# pre-commit hook 설정echo "npx lint-staged" > .husky/pre-commit# pre-push hook 설정echo "npm run lint" > .husky/pre-push
결과적으로 다음과 같은 파일이 생성됩니다.
#!/usr/bin/env sh. "$(dirname -- "$0")/_/husky.sh"npx lint-staged
#!/usr/bin/env sh. "$(dirname -- "$0")/_/husky.sh"npm run lint
커밋 컨벤션 강제하기 (선택 사항)
1. commitlint 패키지 설치
npm i -D @commitlint/cli @commitlint/config-conventional
2. commitlint.config.js 설정
module.exports = {extends: ['@commitlint/config-conventional'],rules: {'type-enum': [2,'always',['feat', 'fix', 'docs', 'style', 'refactor', 'test', 'chore', 'revert', 'design', 'rename'],],},};
3. commit-msg hook 추가
npx husky add .husky/commit-msg 'npx --no-install commitlint --edit $1'