LoginSignup
6
0

More than 1 year has passed since last update.

huskyとlint-stagedを使ってlint errorが発生していたらcommitできないようにしよう

Last updated at Posted at 2021-12-06

パーソンリンクアドベントカレンダー6日目の記事です!

前提

  • eslintは導入済み

以下のようなディレクトリ構成で行いました。

.
├── front
└── server

手順

まずfront配下でライブラリのインストール

yarn add -D husky lint-staged

huskyの初期化コマンドの実行

npx husky-init && yarn

package.jsonをカスタマイズ

{
  "scripts": {
    ...
    "lint": "eslint . --ext ts --ext vue --ext js",
    "prepare": "cd .. && husky install front/.husky",
    "lint-staged": "lint-staged"
  },
  "husky": {
    "hooks": {
      "pre-commit": "lint-staged"
    }
  },
  "lint-staged": {
    "*.@(ts|tsx|vue)": [
      "yarn lint"
    ]
  }
}

下記コマンドを実行

yarn prepare

自動生成された.huskyディレクトリ配下にpre-commitというファイルを作成する

下記の様に記述

pre-commit
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
cd front
yarn lint-staged

最後に下記を実行

cp -r ./front/.husky .

ポイント

package.json.gitのディレクトリが同階層にいないと正常に実行されない為、度々cd frontが挟まれていました。
実際にpre-commitを実行しないと行けないため、最終的にroot階層に.huskycpしました。

動作確認

MacBook-Pro:front $ git commit -m "test"
yarn run v1.22.17
$ lint-staged
✔ Preparing...
⚠ Running tasks...
  ❯ Running tasks for *.@(ts|tsx|vue)
    ✖ yarn lint [FAILED]
↓ Skipped because of errors from tasks. [SKIPPED]
✔ Reverting to original state because of errors...
✔ Cleaning up...

✖ yarn lint:
error Command failed with exit code 1.
$ eslint . --ext ts --ext vue --ext js /Users/user_name/project/example-project/front/components/common/Container.vue

/Users/user_name/project/example-project/front/components/common/Container.vue
  1:1  error  Component name "Container" should always be multi-word  vue/multi-word-component-names

✖ 1 problem (1 error, 0 warnings)

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)

commit前にyarn lint-stagedが実行されており、lint errorが発生している為、commitできないのが確認取れました。

VSCodeでも実際にエラーが出ていることが確認取れました。

スクリーンショット 2021-12-02 10.46.40.png

これでコードレビュー時にlint errorに怯えなくて済みます。。。

参考

https://typicode.github.io/husky/#/
https://zenn.dev/seya/articles/c908d88df0a587
https://kic-yuuki.hatenablog.com/entry/2019/05/27/090515

6
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
0