7
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

はじめに

この記事では、ESLint の Flat Config を利用しているプロジェクトで Prettier を併用する方法について記載します。

元々 ESLint でもフォーマットは可能でしたが、2023年11月にリリースされた v8.53.0 からフォーマットルールが廃止されました。

フォーマットルール廃止についてアナウンスした以下のブログ記事では、代わりに Prettier もしくは dprint の利用を推奨しています。
そのため、今回は Prettier を併用する方法を試してみます。

開発環境

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

  • Windows 11
  • VSCode
  • TypeScript 5.2.2
  • React 18.3.1
  • Vite 5.3.1
  • Node.js 20.15.0
  • npm 10.8.1
  • ESLint 8.57.0
  • Prettier 3.3.2
  • @eslint/js 9.6.0
  • eslint-config-prettier 9.1.0
  • eslint-plugin-react 7.34.3
  • globals 15.8.0
  • typescript-eslint 7.15.0

事前準備

プロジェクトに ESLint のインストール・設定をしておきます。
React / TypeScript 環境における詳細手順はこちら。

Prettier のインストール

Prettier をインストールします。

npm install --save-dev --save-exact prettier

設定ファイル(.prettierrc)を追加します。
以下のコマンドを実行すると、ファイル内に {} とだけ記載されたファイルが作成されます。

node --eval "fs.writeFileSync('.prettierrc','{}\n')"

フォーマット対象外のファイルを指定するファイル(.prettierignore)を作成します。
今回のファイルの中身は Prettier のドキュメントのサンプルと同じ、以下のファイルを指定しておきます。

.prettierignore
# Ignore artifacts:
build
coverage

2024年8月追記
以下のコマンドでも作成できます。

node --eval "fs.writeFileSync('.prettierignore','# Ignore artifacts:\nbuild\ncoverage\n')"

これで Prettier の設定は完了です。
以下のコマンドでフォーマットを実行できます。

npx prettier . --write

eslint-config-prettier のインストール

不要、もしくは Prettier とコンフリクトするルールを無効にするため、eslint-config-prettier をインストールします。

eslint-config-prettier をインストールします。

npm install --save-dev eslint-config-prettier

eslint.config.jseslint-config-prettier を追加します。

eslint.config.js
import globals from "globals";
import pluginJs from "@eslint/js";
import tseslint from "typescript-eslint";
import pluginReactConfig from "eslint-plugin-react/configs/recommended.js";
import pluginReactJSXRuntime from "eslint-plugin-react/configs/jsx-runtime.js";
import eslintConfigPrettier from "eslint-config-prettier"; // Add

export default [
  {
    files: ["**/*.{js,mjs,cjs,ts,jsx,tsx}"],
    settings: {
      react: {
        version: "detect",
      },
    },
  },
  { languageOptions: { parserOptions: { ecmaFeatures: { jsx: true } } } },
  { languageOptions: { globals: globals.browser } },
  pluginJs.configs.recommended,
  ...tseslint.configs.recommended,
  pluginReactConfig,
  pluginReactJSXRuntime,
  eslintConfigPrettier, // Add
];

eslintConfigPrettier は設定を上書きしたい他の設定の後に記載する必要があります。

冒頭で述べた通り ESLint v8.53.0 で ESLint のフォーマットに関するルールは廃止されたので、そもそもこの手順は省いても問題ないかもと思いましたが、eslint-config-prettier のドキュメントにも eslint.config.js(Flat Config)でも設定方法が記載してあったので、今回は設定してみました。

これで設定は完了です。

参考

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?