•10 min read

ViteとESLint、PrettierをReactプロジェクト用に設定する

ViteとESLint、PrettierをReactプロジェクト用に設定する

現代のReactプロジェクトをセットアップするには、ボイラープレートをスキャフォールディングするだけでは不十分です。コード品質と一貫性のための堅牢で強制力のある基盤が求められます。Viteは、比類のない開発速度と直感的な設定システムを提供し、現代のWebアプリケーションの主要なビルドツールとしての地位を確立しました。しかし、進化するコード品質ツール、特にESLintの新しいFlat Configシステムと厳格なTypeScriptコンパイルと統合することは、経験豊富な開発者にとっても課題となることがあります。

この包括的なガイドでは、Vite、ESLintのFlat Config(eslint.config.js)、Prettier、およびTypeScriptを使用して、非常に厳格でモダンなリンティングおよびフォーマットパイプラインを設計します。このアプローチでは、従来の.eslintrc形式を廃止し、統一されたモジュール式のFlat Configを採用することで、設定が将来にわたって有効で高性能であることを保証します。

Audio Briefing
0:00 / 0:00

パラダイムシフト:ESLint Flat Config

これまで、ESLintの設定は.eslintrcファイルを使用したカスケード解決システムに依存しており、複数の設定ファイルが同じディレクトリに適用される場合に混乱を招くことがよくありました。Flat Configシステムは、プロジェクトのルートに単一のeslint.config.jsファイル(または.mjs/.cjs)を使用することで、これを完全に刷新します。このシステムは、設定オブジェクトの配列を順次評価し、ルールを定義するための決定的でプログラム的なアプローチを提供します。

Flat Configシステムは、extendsおよびpluginsの解決の複雑さを排除し、標準のJavaScriptインポートに置き換えます。このパラダイムシフトは、リンティングルールを標準のJavaScriptオブジェクトを構成要素として構築することを意味し、型安全性とルール定義のより明確な系統を提供します。

Advertisement

プロジェクトの初期化

まず、ReactとTypeScriptテンプレートを使用して新しいViteプロジェクトをブートストラップしましょう。

npm create vite@latest modern-react-app -- --template react-ts
cd modern-react-app
npm install

基盤ができたので、リンティングとフォーマットのパイプラインに必要な依存関係をインストールする必要があります。モダンなFlat Configをターゲットとしているため、ESLintの最新バージョンと関連するTypeScriptおよびReactプラグインが必要です。

npm install -D eslint prettier eslint-config-prettier eslint-plugin-react eslint-plugin-react-hooks eslint-plugin-react-refresh @eslint/js typescript-eslint globals

ESLint Flat Configの設計

プロジェクトのルートにeslint.config.jsファイルを作成します。このファイルは設定オブジェクトの配列をエクスポートします。ESLintとTypeScriptのAST間のギャップを埋めるためにtypescript-eslintを活用し、型認識リンティングルールを強制できるようにします。

import js from '@eslint/js';
import globals from 'globals';
import reactPlugin from 'eslint-plugin-react';
import reactHooksPlugin from 'eslint-plugin-react-hooks';
import reactRefreshPlugin from 'eslint-plugin-react-refresh';
import tseslint from 'typescript-eslint';
import prettierConfig from 'eslint-config-prettier';

export default tseslint.config(
  // Base Ignore Configuration
  { ignores: ['dist', 'node_modules', 'coverage', 'vite.config.ts'] },
  
  // Base JavaScript rules
  js.configs.recommended,
  
  // TypeScript Configuration (Strict + Type Checked)
  ...tseslint.configs.strictTypeChecked,
  ...tseslint.configs.stylisticTypeChecked,
  {
    languageOptions: {
      parserOptions: {
        project: ['./tsconfig.app.json', './tsconfig.node.json'],
        tsconfigRootDir: import.meta.dirname,
      },
    },
  },
  
  // React and Environment Configuration
  {
    files: ['**/*.{ts,tsx}'],
    languageOptions: {
      ecmaVersion: 2023,
      sourceType: 'module',
      globals: {
        ...globals.browser,
        ...globals.es2021,
      },
      parserOptions: {
        ecmaFeatures: {
          jsx: true,
        },
      },
    },
    plugins: {
      react: reactPlugin,
      'react-hooks': reactHooksPlugin,
      'react-refresh': reactRefreshPlugin,
    },
    settings: {
      react: {
        version: 'detect',
      },
    },
    rules: {
      ...reactPlugin.configs.recommended.rules,
      ...reactPlugin.configs['jsx-runtime'].rules,
      ...reactHooksPlugin.configs.recommended.rules,
      'react-refresh/only-export-components': [
        'warn',
        { allowConstantExport: true },
      ],
      // Strict React Rules
      'react/prop-types': 'off', // Rely on TypeScript instead
      'react/no-array-index-key': 'error', // Prevent subtle rendering bugs
      'react/jsx-pascal-case': 'error',
      'react/jsx-no-useless-fragment': 'warn',
    },
  },
  
  // Prettier Integration (Must be last to override formatting rules)
  prettierConfig
);

設定の分析

  1. 型認識リンティング: tseslint.configs.strictTypeCheckedを利用することで、TypeScriptの型チェッカーを利用するルールを有効にします。これには、parserOptionsでprojectプロパティを指定し、TypeScriptの設定を指す必要があります。この設定は、安全でないany型、浮動するPromise、誤ったテンプレートリテラル使用法など、深いアーキテクチャ上の欠陥を捕捉します。
  2. React 17+ JSX変換: reactPlugin.configs['jsx-runtime'].rulesを含めることで、ESLintがモダンなJSX変換を理解し、Reactインポートの欠落に関する誤検知を防ぎます。
  3. React Refresh: ViteのFast Refreshメカニズムは、予測可能なコンポーネントのエクスポートに依存しています。react-refresh/only-export-componentsルールは、コンポーネントを含むモジュールがコンポーネントのみをエクスポートすることを強制し、Fast Refreshが確実に動作するようにします。
  4. Prettier統合: eslint-config-prettierプラグインは配列の最後に付加されます。Flat Configシステムはオブジェクトを順次評価するため、最後のオブジェクトが優先されます。これにより、Prettierのフォーマットの意見と衝突する可能性のあるESLintルールは事実上無効になります。

Prettierの設定

Prettierは最小限の設定で済みますが、標準化することで開発環境全体で一貫性が確保されます。ルートディレクトリに.prettierrcファイルを作成します。

{
  "semi": true,
  "trailingComma": "all",
  "singleQuote": true,
  "printWidth": 90,
  "tabWidth": 2,
  "endOfLine": "lf",
  "jsxSingleQuote": false,
  "arrowParens": "always"
}

さらに、生成されたアセットと設定ファイルを除外するために.prettierignoreファイルを定義します。

dist
coverage
node_modules
*.html
vite.config.ts
Advertisement

厳格なTypeScriptの強制

型認識リンティングの利点を最大限に引き出すには、TypeScriptの設定も同様に厳格である必要があります。tsconfig.app.json(最近のViteテンプレートで標準化されている)を修正して、厳格な型チェックを強制します。

{
  "compilerOptions": {
    "target": "ES2020",
    "useDefineForClassFields": true,
    "lib": ["ES2020", "DOM", "DOM.Iterable"],
    "module": "ESNext",
    "skipLibCheck": true,

    /* Bundler mode */
    "moduleResolution": "bundler",
    "allowImportingTsExtensions": true,
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx",

    /* Strict Type-Checking Options */
    "strict": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "noFallthroughCasesInSwitch": true,
    "noImplicitAny": true,
    "strictNullChecks": true,
    "strictFunctionTypes": true,
    "strictBindCallApply": true,
    "strictPropertyInitialization": true,
    "noImplicitThis": true,
    "alwaysStrict": true,
    "noUncheckedIndexedAccess": true, // Highly recommended for array access safety
    "exactOptionalPropertyTypes": true
  },
  "include": ["src"]
}

noUncheckedIndexedAccessの追加は非常に重要です。これにより、開発者は配列またはレコード要素にインデックスでアクセスする際に未定義のケースを処理することを強制され、TypeScriptの静的解析とランタイムの現実との間の一般的なギャップを埋めます。

Viteとの統合

IDE統合はインラインリンティングを処理しますが、ESLintをViteビルドプロセスに直接統合することで、リンティングエラーが残っている場合にCI/CDパイプラインと本番ビルドが失敗するようにします。

これを実現するために、vite-plugin-eslintを利用できます。ただし、Flat Configへの移行に伴い、プラグインまたはカスタムのRollupプラグインがESLint 9+とFlat Config APIをサポートしていることを確認する必要があります。あるいは、ビルド前のステップとしてリンティングを実行することは、非常に堅牢なアプローチです。

package.jsonスクリプトを更新します。

{
  "scripts": {
    "dev": "vite",
    "build": "npm run typecheck && npm run lint && vite build",
    "lint": "eslint .",
    "lint:fix": "eslint . --fix",
    "format": "prettier --write \"src/**/*.{ts,tsx,css,md}\"",
    "typecheck": "tsc --noEmit -p tsconfig.app.json && tsc --noEmit -p tsconfig.node.json",
    "preview": "vite preview"
  }
}

このシーケンスにより、npm run buildはアプリケーションをバンドルしようとする前に型チェックとリンティングを実行することが保証されます。厳格な型ルールまたはリンティングポリシーに違反があった場合、ビルドは中止されます。

結論

ESLintのFlat ConfigをViteおよびPrettierと組み合わせて移行することで、モダンなReact開発の明確な標準が確立されます。typescript-eslintを介した型認識リンティングに大きく傾倒し、厳格なTypeScriptコンパイラオプションを強制することで、チームはランタイムエラーのクラス全体を事前に排除できます。この設定は、決定的で高性能、かつ将来にわたって有効な基盤を提供し、開発者がコードスタイルについて議論したり、微妙な型付けのバグを追いかけたりするのではなく、アーキテクチャの複雑さに集中できるようにします。

こちらもおすすめ

Share this article:

Stay Updated

Get the latest posts delivered straight to your inbox.

Free Developer Utilities

Free In-Browser Developer Tools

Clean AI CLI logs, build cron expressions, decode JWTs, and calculate chmod permissions offline.

Explore Tools
Advertisement