LoginSignup
3
3

More than 1 year has passed since last update.

commit時にESlintとPrettierを実行する【ESLint】【Prettier】

Last updated at Posted at 2022-05-11

はじめに

git commitをした際にeslint --fixprettier --writeを実行する方法について記載します。

パッケージのインストール

以下のコマンドを実行してhuskyおよびlint-stagedをインストールします。

ターミナル
$ yarn add -D husky lint-staged

lint-stagedの設定

lint-stagedの設定をします。
package.json に以下のように記述することでステージングしたファイルに対しコマンドを実行できます。

package.json
  "lint-staged": {
    "*.{js,jsx,ts,tsx}": [
      "eslint --fix",
      "prettier --write"
    ]
  },

Git hooksを有効化

以下コマンドを実行してGit hooksを有効化します。

ターミナル
yarn husky install

以下のように.huskyディレクトリが作成されます。
スクリーンショット 2022-05-12 午前2.42.37.png

git cloneしてパッケージをインストールした際にGit hooksを有効化するため、package.jsonprepareを記述します。

yarn2以降を使用している場合にはprepareは使用でないのでpostinstallを記述します。

package.json
  "scripts": {
    "prepare": "husky install"
  },
package.json
  "scripts": {
    "postinstall": "husky install"
  },

hooksを作成

以下のコマンドを実行してhooksを作成します。

ターミナル
$ yarn husky add .husky/pre-commit "npx lint-staged"

実行すると.huskyディレクトリにpre-commitファイルが作成されます。

スクリーンショット 2022-05-12 午前2.50.15.png

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

npx lint-staged

確認

正常に動作する確認します。

ターミナル
$ git add .

$ git commit -m "test"
✔ Preparing lint-staged...
✔ Hiding unstaged changes to partially staged files...
✔ Running tasks for staged files...
✔ Applying modifications from tasks...
✔ Restoring unstaged changes to partially staged files...
✔ Cleaning up temporary files...
[main bf38a3f] test
 1 file changed, 1 insertion(+), 1 deletion(-)
3
3
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
3
3