LoginSignup
2
2

More than 1 year has passed since last update.

ESLint と Prettier の導入

Last updated at Posted at 2023-02-23

はじめに

ESLint と Prettier の導入手順のメモです。

開発環境は以下の通りです。

  • Windows11
  • VSCode
  • Vite 4.1.0

ESLint

まずはESLintをインストールします。
公式ドキュメントに沿って、以下のコマンドでインストールします。

npm init @eslint/config

インストールの途中でいくつか質問されます。

スタイル(フォーマット)は、Prettierに任せたいので、To check syntax and find problems を選択します。
image.png
tsconfig.json"module"ESNext なので、JavaScript modules(import/export) を選択します。
image.png
React を選択します。
image.png
TypeScript を利用しているので、Yes を選択します。
image.png
Browser を選択します。
image.png
JSON を選択します。
image.png
ReactやTypeScript向けのプラグインのインストールを求められるので、Yes を選択します。
image.png
yarn を選択します。
image.png

これでインストールが完了します。

インストール時の質問内容については、Setting up ESLINT in your JavaScript Project with VS Code で解説されています。

インストールが完了すると、新たに .eslintrc.json が作成されます。

.eslintrc.json
{
  "env": {
    "browser": true,
    "es2021": true
  },
  "extends": [
    "eslint:recommended",
    "plugin:react/recommended",
    "plugin:@typescript-eslint/recommended"
  ],
  "overrides": [],
  "parser": "@typescript-eslint/parser",
  "parserOptions": {
    "ecmaVersion": "latest"
  },
  "plugins": ["react", "@typescript-eslint"],
  "rules": {}
}

また、package.jsondevDependencies には、以下の4つが追加されます。

  • "@typescript-eslint/eslint-plugin": "^5.52.0"
  • "@typescript-eslint/parser": "^5.52.0"
  • "eslint": "^8.34.0"
  • "eslint-plugin-react": "^7.32.2"
package.json
"devDependencies": {
  "@types/react": "^18.0.27",
  "@types/react-dom": "^18.0.10",
  "@typescript-eslint/eslint-plugin": "^5.52.0",
  "@typescript-eslint/parser": "^5.52.0",
  "@vitejs/plugin-react": "^3.1.0",
  "eslint": "^8.34.0",
  "eslint-plugin-react": "^7.32.2",
  "typescript": "^4.9.3",
  "vite": "^4.1.0"
}

ESLintが正しくインストールされたか、以下のコマンドでバージョンを表示して確認できます。

npx eslint -v

image.png

Prettier

Prettierの設定をしていきます。
公式ドキュメントに沿って、以下のコマンドでインストールします。

yarn add --dev --exact prettier

Prettierが正しくインストールされたか、以下のコマンドでバージョンを表示して確認できます。

yarn prettier -v

image.png

次にプロジェクトルートに設定ファイルとして、.prettierrc.json を作成します。
加えて、フォーマット対象外のファイルを指定するために .prettierignore を作成します。
それぞれ設定したい内容がある場合、各ファイルに記載します。

eslint-config-prettierの追加

ここまでの手順でESLintとPrettierの導入はできました。
ただ、このままでは、ESLintとPrettierのフォーマットルールが競合してしまいます。

そのため、最後にその対策を行います。
Prettierの公式ドキュメントには、フォーマットはPrettierを、バグ検知はリンターを使うということが記載してあります。

use Prettier for formatting and linters for catching bugs!
(Prettier vs. Linters)

したがって、ESLintのフォーマット機能を無効にします。
方法は簡単で eslint-config-prettier を利用します。

まず以下のコマンドでインストールします。

yarn add --dev eslint-config-prettier

その後、.eslint.jsonextend最後"prettier" を追加すれば完了です!

"extends": [
  "eslint:recommended",
  "plugin:react/recommended",
  "plugin:@typescript-eslint/recommended",
  "prettier"
],

参考

2
2
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
2
2