どうもシローです。久しぶりの投稿となりますが、相変わらずエンジニアとして開発ライフを送っております。
最近はフロントエンドの開発に携わることが多く、多くの現場でコミット前にeslintでコードチェックをhuskyで行っているのでその方法を紹介します。
手順
必要なパッケージのインストール
- husky
- lint-staged
- eslint
1 |
$ yarn add -D husky lint-staged eslint |
huskyの設定ファイルを作成
1 2 |
$ npx husky install $ npx husky add .husky/pre-commit "yarn lint-staged" |
これで<project_root>/.husky/pre-commitが生成される
package.jsonを編集
1 2 3 4 5 6 7 8 9 |
{ "scripts": { ..., "lint:precommit": "eslint './**/*.{ts,tsx}' --max-warnings 0", }, "lint-staged": { "./**/*.{ts,tsx}": "yarn lint:precommit" }, } |
以上。
試す
eslintに引っかかる記述のままpre-commitをするとこうなる
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
git commit -m 'chore: test pre-commit' yarn run v1.22.19 $ ~/work/netaverse/front/node_modules/.bin/lint-staged ✔ Preparing lint-staged... ❯ Running tasks for staged files... ❯ package.json — 1 file ❯ ./**/*.{ts,tsx} — 1 file ✖ yarn lint:precommit [FAILED] ↓ Skipped because of errors from tasks. [SKIPPED] ✔ Reverting to original state because of errors... ✔ Cleaning up temporary files... ✖ yarn lint:precommit: ESLint found too many warnings (maximum: 0). error Command failed with exit code 1. $ eslint './**/*.{ts,tsx}' --max-warnings 0 ~/work/netaverse/front/components/templates/TopTemplate.tsx ~/work/netaverse/front/components/templates/TopTemplate.tsx 10:5 warning React Hook useEffect has a missing dependency: 'searchPost'. Either include it or remove the dependency array react-hooks/exhaustive-deps ✖ 1 problem (0 errors, 1 warning) info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command. error Command failed with exit code 1. info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command. husky - pre-commit hook exited with code 1 (error) |
参照
husky :
lint-staged: https://github.com/okonet/lint-staged