目次
概要
開発でリンターを入れている人はいるかと思いますが、eslintコマンドを実行し忘れてPRで指摘されるケースがたまにあります。
それをなくすために、commit前にeslintコマンドを自動実行する方法についてまとめてみました。
準備
React雛形作成
npx create-react-app react-app
起動確認
npm start
リンターの導入
以下対話形式で回答する
npm install eslint --save-dev
npx eslint --init
✔ How would you like to use ESLint? · style
✔ What type of modules does your project use? · esm
✔ Which framework does your project use? · react
✔ Does your project use TypeScript? · No / Yes
✔ Where does your code run? · browser
✔ How would you like to define a style for your project? · guide
✔ Which style guide do you want to follow? · airbnb
✔ What format do you want your config file to be in? · JavaScript
Checking peerDependencies of eslint-config-airbnb@latest
The config that you've selected requires the following dependencies:
eslint-plugin-react@^7.28.0 eslint-config-airbnb@latest eslint@^7.32.0 || ^8.2.0 eslint-plugin-import@^2.25.3 eslint-plugin-jsx-a11y@^6.5.1 eslint-plugin-react-hooks@^4.3.0
✔ Would you like to install them now? · No / Yes
✔ Which package manager do you want to use? · npm
package.jsonに以下を追加
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
+ "lint": "npx eslint . --ext .js",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
リンターの動作確認
npm run lint
リンターが効いていることを確認。
huskyの導入
huskyのインストール
npx husky install
コミット前のhooks作成
npx husky add .husky/pre-commit "npm run lint"
以下が作成される
.husky/pre-commit
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"
npm run lint
検証
git addしてコミットしてみる
git add .
git commit -m "Introduce husky"
> react-app@0.1.0 lint /path/react-app
> npx eslint . --ext .js
git commit時にnpm run lint
コマンドを実行し、lintコマンドが自動実行されることを確認できた。
参考
https://dev.classmethod.jp/articles/pre-commit/
https://fwywd.com/tech/husky-setup