Vapor Trail

明るく楽しく元気よく

VSCode+ESLint+Prettierの設定覚書

Reactで快適に開発するために初期設定をいろいろ試した。 とりあえず余計なものは極力入れないようにした。コーディングルールもrecommendに従う。

ESLintとPrettierをなぜ両方入れるのかよくわかってなかったのでこちらを参考にした。

qiita.com

ESLint と Prettier の共存設定とその根拠について

設定

1. VSCodeでESLint,Prettierプラグインをインストール

2. プロジェクト内で関連モジュールをインストール

$ npm i -D eslint prettier eslint-config-prettier eslint-plugin-import eslint-plugin-jsx-a11y eslint-plugin-prettier eslint-plugin-react eslint-plugin-react-hooks

3. 設定ファイルを書く

.vscode/settings.json

{
  // formatter
  "editor.formatOnSave": true,
  "editor.formatOnPaste": true,
  "editor.formatOnType": true,
  // eslint settings
  "eslint.validate": [
    "javascript",
    "javascriptreact",
    "typescript",
    "typescriptreact"
  ],
  "editor.codeActionsOnSave": {
    "source.fixAll.eslint": true // eslint
  }
}

.eslintrc

{
  "env": {
    "browser": true,
    "es2021": true
  },
  "extends": [
    "eslint:recommended",
    "plugin:react/recommended",
    "plugin:react-hooks/recommended",
    "plugin:prettier/recommended"
  ],
  "parserOptions": {
    "ecmaFeatures": {
      "jsx": true
    },
    "sourceType": "module"
  },
  "plugins": ["react", "react-hooks"],
  "rules": {
    "react/jsx-uses-react": "error",
    "react/jsx-uses-vars": "error",
    "react-hooks/rules-of-hooks": "error", // Checks rules of Hooks
    "react-hooks/exhaustive-deps": "warn" // Checks effect dependencies
  }
}

.prettierrc

{
  "endOfLine": "lf",
  "singleQuote": true
}

4. commit時にlintするようにgit-hookを設定

$ npm i -D husky lint-staged

package.json

{
  "main": "node_modules/expo/AppEntry.js",
  "scripts": {
    "start": "expo start",
    "android": "expo start --android",
    "ios": "expo start --ios",
    "web": "expo start --web",
    "eject": "expo eject"
  },
  "dependencies": {
    "expo": "~39.0.2",
    "expo-status-bar": "~1.0.2",
    "react": "16.13.1",
    "react-dom": "16.13.1",
    "react-native": "https://github.com/expo/react-native/archive/sdk-39.0.3.tar.gz",
    "react-native-web": "~0.13.12"
  },
  "devDependencies": {
    "@babel/core": "~7.9.0",
    "eslint": "^7.10.0",
    "eslint-config-prettier": "^6.12.0",
    "eslint-plugin-import": "^2.22.1",
    "eslint-plugin-jsx-a11y": "^6.3.1",
    "eslint-plugin-prettier": "^3.1.4",
    "eslint-plugin-react": "^7.21.3",
    "eslint-plugin-react-hooks": "^4.1.2",
    "husky": "^4.3.0",
    "lint-staged": "^10.4.0",
    "prettier": "^2.1.2"
  },
  "private": true,
  "plugins": [
    "react",
    "jsx-a11y",
    "import"
  ],
  "husky": {
    "hooks": {
      "pre-commit": "lint-staged"
    }
  },
  "lint-staged": {
    "*.{js,jsx}": [
      "eslint --fix",
      "git add"
    ]
  }
}