6
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

TypeScript環境にESLint+Prettierを最小で導入する

Last updated at Posted at 2020-09-01

TL;DR

今回の設定ファイルは全てこのGistにあります。

はじめに

今回はTypeScript環境にESLint+Prettierをなるべく少ないファイル記述で導入することを目標にします。
他のLinter導入記事を見ていると重複した設定や無意味な設定が目立つのでそういったものは省きつつ導入します。

注: 私自身、Linterの導入になれているわけではないのでおかしい点があったら指摘してください。

パッケージのインストール

今回はyarnを用いますが、お好みでnpmやpnpmを使用しても構いません。

ESLint

yarn add -D eslint @typescript-eslint/parser @typescript-eslint/eslint-plugin
名称 説明
eslint ESLint本体です。これがないと始まりません。
@typescript-eslint/parser ESLintにTypeScriptのソースコードを読み込ませるためのパーサーです。
@typescript-eslint/eslint-plugin TypeScript特有のLintルールを追加します。

Prettier

yarn add -D prettier eslint-config-prettier eslint-plugin-prettier
名称 説明
prettier Prettier本体です。
eslint-config-prettier ESLintとPrettierでルールが競合している箇所を取り除く設定を追加します。
eslint-plugin-prettier ESLint上でPrettierを実行できるようにします。

設定ファイル

ESLint

.eslintrc
{
  "env": {
    "node": true,  // Node.js特有のグローバル変数を有効にします。
    // "browser": true,  // ブラウザ環境で動作するコードにLintを実行する場合は"node"をfalseに設定し"browser"をtrueにしてください。
    "es2020": true  // ES2020特有のグローバル変数及び構文を有効にします。
  },
  "plugins": ["@typescript-eslint"],
  "parser": "@typescript-eslint/parser",  // TypeScript用のパーサーを使用します。
  "parserOptions": {
    "sourceType": "module"  // ソースコードをESModuleとして読み込みます。
  },
  "extends": [
    "eslint:recommended",  // ESLintの基本的なルールを有効にします。
    "plugin:@typescript-eslint/recommended",  // TypeScriptの基本的なルールを有効にします。
    "plugin:prettier/recommended",  // Prettierと競合するESLintのルールを無効にします。
    "prettier/@typescript-eslint"  // Prettierと競合するTypeScriptの基本的なルールを無効にします。
  ]
}

Prettier

Prettierの設定はあくまで一例です。好みに合わせて設定ファイルを変更してください。

.prettierrc
{
  "arrowParens": "always",  // アロー関数の引数が1つだった場合もカッコを強制する(差分を少なくするため)。
  "printWidth": 100,  // 折り返すまでの文字数を100に設定する。
  "trailingComma": "all"  // 複数行に渡る配列やオブジェクトのカンマを末尾にも強制する(差分を少なくするため)。
}

npmスクリプト

package.json
{
  "scripts": {
    // .gitignoreに記載されていない全てのTSファイルに対してLintを実行する。
    "eslint": "eslint --ignore-path .gitignore '**/*.ts'",
    // 上記と同様だが、修正可能なエラーは修正する。
    "eslint:fix": "eslint --ignore-path .gitignore '**/*.ts' --fix"
  }
}
6
3
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
6
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?