LoginSignup
265
214

More than 3 years have passed since last update.

VSCodeでESLint+typescript-eslint+Prettierを導入する(2020/11/14修正)

Last updated at Posted at 2019-03-03

追記: eslint-plugin-prettierは非推奨なので内容を修正しました。prettierはeslintを通して実行するよりも、VSCode側から実行するほうが良いです。

前置き

TypeScriptチームがESLintのTypeScript対応を強化するとの発表がありました。
これまでTypeScriptといえばTSLintでしたが、これからはESLintがメインになっていくと思われます。
そもそもESLintってなに? という方はこちら

インストール

eslint

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

prettier

yarn add -D prettier eslint-config-prettier

基本設定

.eslintrc.json
{
  "extends": [
    "eslint:recommended",
    "plugin:@typescript-eslint/recommended",
    "prettier",
    "prettier/@typescript-eslint"
  ],
  "plugins": ["@typescript-eslint"],
  "parser": "@typescript-eslint/parser",
  "parserOptions": {
    "sourceType": "module"
  },
  "env": { "browser": true, "node": true, "es6": true },
  "rules": {
    // 適当なルール
  }
}

型情報が必要なルールを使用する場合(パフォーマンス注意)

.eslintrc.json
{
  "extends": [
    "eslint:recommended",
    "plugin:@typescript-eslint/recommended",
    "plugin:@typescript-eslint/recommended-requiring-type-checking",
    "prettier",
    "prettier/@typescript-eslint"
  ],
  "plugins": ["@typescript-eslint"],
  "parser": "@typescript-eslint/parser",
  "parserOptions": {
    "sourceType": "module",
    "project": "./tsconfig.json"
  },
  "env": { "browser": true, "node": true, "es6": true },
  "rules": {
    // 適当なルール
  }
}
  • "plugin:@typescript-eslint/recommended"
    • 型を必要としない基本ルールを詰め込んだもの
  • "plugin:@typescript-eslint/recommended-requiring-type-checking"
    • 型情報が必要な基本ルールを詰め込んだもの
    • TypeScriptのビルド時間分が増えるので、パフォーマンスが気になる場合外す
  • "plugin:@typescript-eslint/eslint-recommended"
    • TypeScriptでチェックされる項目を除外する設定
    • recommendedとrecommended-requiring-type-checkingに含まれているので、どちらかを使うなら記述する必要は無いです

個別設定例

.eslintrc.json
{
  "rules": {
    "@typescript-eslint/explicit-module-boundary-types": "off",
    "@typescript-eslint/array-type": [
      "error",
      {
        "default": "array-simple"
      }
    ]
  }
}

必要であれば、TSLintとの対照表を確認しながら設定しましょう。
@typescript-eslint/eslint-plugin-tslintを追加することでtslintの設定も使用できます。

ルールの詳細はこちらを確認しましょう。

VSCode

ESLint拡張機能Prettier拡張機能をインストールしてください。

settings.json
{
  "editor.formatOnSave": true,
  "editor.defaultFormatter": "esbenp.prettier-vscode",
  "editor.codeActionsOnSave": {
    "source.fixAll.eslint": true
  },
}

VS Code ESLint extension2.0.4からeslint.validateは不要になりました。

参考

https://teppeis.hatenablog.com/entry/2019/02/typescript-eslint
https://github.com/typescript-eslint/typescript-eslint/releases

265
214
3

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
265
214