0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Vite】Reactアプリに自動フォーマッター「Prettier」を導入する方法

Posted at

Reactアプリに自動フォーマッター「Prettier」を導入する方法について記載します。

Prettier

今回は、①すでにESLintが設定済みを前提とした場合、②Prettierのみの場合の2パターンについて説明していきます。

①すでにESLintが設定済みを前提とした場合

1.必要なパッケージをインストール

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

prettier … コード整形用
eslint-config-prettier … ESLint のフォーマット系ルールを Prettier に委譲して競合回避
eslint-plugin-prettier … Prettier を ESLint のルールとして統合

2.Prettier 設定ファイルを作成

プロジェクトルートに.prettierrcを作ります。

.prettierrc
{
  "semi": true,
  "singleQuote": true,
  "trailingComma": "all",
  "printWidth": 100,
  "tabWidth": 2
}

必要に応じて.prettierignoreを作り、整形したくないフォルダを指定します。

.prettierignore
node_modules
dist
build

3.ESLint と Prettier の統合

eslint.config.js
import prettierPlugin from 'eslint-plugin-prettier';
import { defineConfig } from 'eslint/config';

export default defineConfig({
  // 既存の plugins に追加
  plugins: {
    //すでに組み込まれているplugins,
    prettier: prettierPlugin,
  },
  // 既存の rules に追加
  rules: {
    //すでに組み込まれているrules,
    'prettier/prettier': 'error', // Prettier のルール違反を ESLint エラーとして扱う
  },
  // 競合回避のための extends
  extends: [
    // 既存の extends
    'prettier', // これで ESLint のフォーマット系ルールを無効化
  ],
});

全体のコードは下記⇩

eslint.config.js
// eslint.config.js
import js from '@eslint/js';
import globals from 'globals';
import reactPlugin from 'eslint-plugin-react';              // 👈 ←これを追加!
import reactHooks from 'eslint-plugin-react-hooks';         // 👈 ←これを追加!
import reactRefresh from 'eslint-plugin-react-refresh';     // 👈 ←これを追加!
import jsxA11y from 'eslint-plugin-jsx-a11y';               // 👈 ←これを追加!
import tseslint from 'typescript-eslint';
import { defineConfig, globalIgnores } from 'eslint/config';

export default defineConfig([
  globalIgnores(['dist']),
  {
    files: ['**/*.{ts,tsx}'],
    languageOptions: {
      ecmaVersion: 2020,
      globals: globals.browser,
      parser: tseslint.parser,
      parserOptions: {                                      // 👈 ←これを追加!
        ecmaFeatures: { jsx: true },
      },
    },
    plugins: {
      '@typescript-eslint': tseslint.plugin,                // 👈 ←これを追加!
      react: reactPlugin,
      'react-hooks': reactHooks,
      'jsx-a11y': jsxA11y,                                  // 👈 ←これを追加!
      'react-refresh': reactRefresh,                        // 👈 ←これを追加!
      prettier: prettierPlugin,                             // 🌟 ←これを追加!
    },
    // 👇 “extends”の代わりに configs を展開する
    rules: {
      ...js.configs.recommended.rules,
      ...tseslint.configs.recommended[1].rules, // 👈tseslintは配列形式
      ...reactPlugin.configs.recommended.rules,
      ...reactHooks.configs['recommended-latest'].rules,
      ...jsxA11y.configs.recommended.rules,
      ...reactRefresh.configs.vite.rules,
      'react/react-in-jsx-scope': 'off',
      '@typescript-eslint/no-unused-vars': 'warn',
      'prettier/prettier': 'error',                           // 🌟Prettier のルール違反を ESLint エラーとして扱う
    },
    settings: {
      react: {
        version: 'detect',
      },
    },
    extends: [                                    // 🌟 ←これを追加!
    'prettier', // これで ESLint のフォーマット系ルールを無効化
  ],
  },
]);

ポイント

1.eslint-config-prettier(extends: "prettier")で ESLint のコード整形系ルールを無効化

2.eslint-plugin-prettier ('prettier/prettier': 'error') で Prettier 違反を ESLint で検出

4.コマンドで実行

整形チェック

npx prettier --check "src/**/*.{ts,tsx,js,jsx,json,css,md}"

自動整形

npx prettier --write "src/**/*.{ts,tsx,js,jsx,json,css,md}"

package.json にスクリプトを追加(これすと便利です)

package.json
"scripts": {
  "lint": "eslint . --ext .ts,.tsx,.js,.jsx",
  "format": "prettier --write 'src/**/*.{ts,tsx,js,jsx,json,css,md}'",
  "format:check": "prettier --check 'src/**/*.{ts,tsx,js,jsx,json,css,md}'"
}

VS Code で自動整形

「Prettier - Code formatter」をインストール

設定で"editor.formatOnSave": trueにする

保存時に ESLint + Prettier の整形が自動で適用されます

Prettierのみの場合

1.Prettier のインストール

まずプロジェクトに Prettier を開発依存としてインストールします。

npm install --save-dev prettier

設定ファイルの作成

プロジェクトルートに .prettierrc という名前で設定ファイルを作ります。

.prettierrc
{
  "semi": true,
  "singleQuote": true,
  "trailingComma": "all",
  "printWidth": 100,
  "tabWidth": 2
}

設定の意味

1.semi: true → 行末にセミコロンを付ける
2.singleQuote: true → 文字列はシングルクォート
3.trailingComma: all → 配列・オブジェクトの最後にもカンマ
4.printWidth: 100 → 1行の最大幅 100
5.tabWidth: 2 → インデント幅 2 スペース

3.prettierignore の作成(任意)

整形したくないフォルダやファイルを.prettierignoreに指定できます。

.prettierignore
node_modules
dist
build

4.Prettier をコマンドで実行

全ファイルをチェック

npx prettier --check "src/**/*.{ts,tsx,js,jsx,json,css,md}"

5.自動整形

npx prettier --write "src/**/*.{ts,tsx,js,jsx,json,css,md}"

--check → 整形されていない箇所を確認

--write → 実際に整形して上書き

6.package.json にスクリプトを追加(便利)

package.json
"scripts": {
  "format": "prettier --write 'src/**/*.{ts,tsx,js,jsx,json,css,md}'",
  "format:check": "prettier --check 'src/**/*.{ts,tsx,js,jsx,json,css,md}'"
}

npm run format → 自動整形

npm run format:check → チェックのみ

サイト

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?