LoginSignup
1
0

Reactにhuskyを導入してコミット時にコードを綺麗にする

Posted at

毎回新規プロジェクトを作ると設定を忘れるので、記録。
huskyとそれに付随して使うものを合わせて設定する。
今回はyarnを使ってのインストール。

必要なものをインストール

husky

yarn add --dev husky

lint-staged

ステージされているファイルにフォーマッタをかける

yarn add --dev lint-staged

ESLintとPrettier

リンターとフォーマッタ

yarn add --dev eslint prettier eslint-config-prettier

Git hooksを有効にする

// npm 
npx husky install 

// yarn 
yarn run husky install

ESLintとPrettierの設定

yarn run eslint --init

色々聞かれるので、目的にあった選択肢を確定していく。

Prettierの設定ファイル.prettierrcをプロジェクトのルートに作成する。

{
// 1行の文字数
  "printWidth": 120,
  // シングルクォートを許容するか
  "singleQuote": true,
  // 文末のセミコロンをどうするか
  "semi": false
}

hooksの作成

作成する前にgit initでgitを使用できる状態にすること。

yarn husky init

.husky以下にpre-commitファイルができるので、編集する。

yarn test

npx lint-staged

package.jsonに設定を追加

"scripts": {
  "lint-fix": "eslint --fix './src/**/*.{js,ts,tsx}' && prettier --write './src/**/*.{js,ts,tsx}'"
},

"eslintConfig": {
  "extends": [
    "react-app",
    "react-app/jest"
  ]
}

  "husky": {
    "hooks": {
      "pre-commit": "lint-staged"
    }
  },
  "lint-staged": {
    "src/**/*.{js,ts,tsx}": [
      "yarn lint-fix"
    ]
 }

補足

.eslintrcを編集する。

"extends": [  
    "eslint:recommended",  
    "plugin:@typescript-eslint/recommended",  
    // "plugin:react/recommended" ←削除 
  "prettier"  ←追加
],

"plugin:react/recommended"を削除しないと、'React' must be in scope when using JSXのエラーがでる。

公式を見ると、React v17から仕様変更されているため、このエラーが出るようだ。

eslint-plugin-react を使用している場合、react/jsx-uses-react と react/react-in-jsx-scope のルールは不要になりますので、無効にするか削除することができます。

参考
https://zenn.dev/otomoti_27/articles/692e1308ce849b

1
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
1
0