LoginSignup
0

More than 3 years have passed since last update.

概要

あんまりlintの設定周りを自分でやってこなかったのでまとめる
あくまで自分用のメモ

前提条件

create-react-appで作成したproject(TypeScript)におけるlintの設定とする

使うやつ

  • eslint
    • linter
    • 構文解析してコードの秩序を保つ
  • prettier
    • code formatter
    • コード整形してコードをきれいな状態に保つ

eslint/prettier関連の設定

インストールコマンド

yarn add -D @typescript-eslint/eslint-plugin @typescript-eslint/parser 
prettier eslint-config-prettier eslint-plugin-prettier

[注意] eslintはcreate-react-app(react-script)経由で入っているので、別途インストールするとbuildエラーになる(場合がある ※ react-scriptが依存しているeslintと別途入れたeslintのバージョンが異なる場合)

設定ファイルの作成

.eslintrc
{
  "parser": "@typescript-eslint/parser",
  "parserOptions": {
    "project": "./tsconfig.json",
    "tsconfigRootDir": "."
  },
  "plugins": ["@typescript-eslint", "prettier"],
  "extends": [
    "plugin:@typescript-eslint/recommended",
    "plugin:prettier/recommended",
    "prettier/@typescript-eslint",
    "plugin:react/recommended"
  ],
  "rules": {
    "prettier/prettier": "error"
  }
}
.prettierrc
{
  "tabWidth": 2,
  "semi": false,
  "singleQuote": true
}

※ ココらへんは好みや宗教による

VS Codeの設定

VS Codeを利用している場合は以下の設定で保存時にコード整形をすることができる

Extensions

以下のExtensionをインストールする

settings.json

以下の設定を追加

settings.json
  // 以下のファイルタイプは環境に合わせる
  "[typescript]": {
    "editor.formatOnSave": true
  },
  "[typescriptreact]": {
    "editor.formatOnSave": true
  },
  "eslint.validate": [
    "javascript",
    "javascriptreact",
    {
        "language": "typescript",
        "autoFix": true
    },
    {
        "language": "typescriptreact",
        "autoFix": true
    }
  ],

lint-staged/huskyの設定

git commit前にeslint --fixを実行して汚いコードが混入することを防ぐ

インストール

コマンド

yarn add -D lint-staged husky

package.jsonの設定

package.jsonに以下の設定を追加

package.json
  "husky": {
    "hooks": {
      "pre-commit": "lint-staged"
    }
  },
  "lint-staged": {
    "linters": {
      "src/**/*.{ts,tsx}": [
        "eslint --fix",
        "git add"
      ]
    }
  },

まとめ(小並感)

  • lintの設定あんまりやったことないけど一通りやって完全に理解した
  • こういうのはフレームワークで吸収してほしいなぁ(Next.jsでどうなってるか調べてみる)
  • 複数人や開発するときはやっぱりあったほうがいいね

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
0