2-2:ESLintとPrettierの環境設定

当サイトではアフィリエイト広告を利用して商品を紹介しています。
当サイトではアフィリエイト広告を利用して商品を紹介しています。

ESLintとPrettierと各関連パッケージの環境設定をします。
ESLintとはJavaScriptコードの問題を見つけて修正する静的解析ツールです。Prettierとはコードのインデント、改行などを自動整形してくれるコードフォーマッターです。

ESLint関連の環境設定

ESLint関連のインストール

typescript-eslintのサイトを参考にESLint関連のパッケージ類を一気にインストールします。
まずはステップ1に記載されているコマンドからすでにインストールしているtypescriptを削除して以下のようにターミナルで実行します。以下のコマンドを実行します。

npm i -D eslint @typescript-eslint/parser @typescript-eslint/eslint-plugin

ESLint設定ファイルを作成

typescript-eslintのサイトのステップ2を参考にして.eslintrc.jsというファイル名でESLint設定ファイルを作成します。ESLint設定ファイル名が.eslintrc.cjsと記載されていますが気にせず.eslintrc.jsを作成します。以下のコマンドをターミナルで実行します。

touch .eslintrc.js

.eslintrc.jsが作成されたら以下のコードを入力して保存します。

module.exports = {
	extends: ['eslint:recommended', 'plugin:@typescript-eslint/recommended'],
	parser: '@typescript-eslint/parser',
	plugins: ['@typescript-eslint'],
	root: true,
};

Prettier関連の環境設定

Prettier関連のインストール

ESLintと同様にPrettier関連のパッケージ類を一気にインストールします。以下のコマンドをターミナルで実行します。

npm i -D prettier eslint-config-prettier

ESLint設定ファイルに設定を追加

eslint-config-prettierのサイトを参考にして.eslintrc.jsのextendsにprettierを追加します。

module.exports = {
 	extends: [
  		"eslint:recommended",
  		"plugin:@typescript-eslint/recommended",
  		"prettier",	// ここに追加
 	],
 	parser: '@typescript-eslint/parser',
  	plugins: ['@typescript-eslint'],
	root: true,
};

またこのままだとエラーが発生する場合があります。そこで以下のように.eslintrc.jsに追加します。

module.exports = {
 	extends: [
  		"eslint:recommended",
  		"plugin:@typescript-eslint/recommended",
  		"prettier",
 	],
 	parser: '@typescript-eslint/parser',
  	plugins: ['@typescript-eslint'],
	root: true,
 	// ここから追加
  	env: {
  		node: true,
	},
};

Prettier設定ファイルを作成

Prettier – Configuration File を参考にして.prettierrc.jsというファイル名でPrettier設定ファイルを作成します。以下のコマンドをターミナルで実行します。

touch .prettierrc.js

.prettierrc.jsが作成されたら以下のコードを入力して保存します。

module.exports = {
	trailingComma: "es5",
	tabWidth: 2,
	semi: false,
	singleQuote: true,
};
タイトルとURLをコピーしました