発生したエラー
まず、エラー発生した環境は以下の通り。2 つの Vite React-TS をモノレポ管理している:
{プロジェクトフォルダ}
┣ web-react-01
┗ web-react-02
モノレポ管理している上記 2 つの Vite React-TS の両方から、以下のエラーが表示された。
Parsing error: No tsconfigRootDir was set, and multiple candidate TSConfigRootDirs are present:
C:\GitHub\{プロジェクトフォルダ}\web-react-01
C:\GitHub\{プロジェクトフォルダ}\web-react-02
You'll need to explicitly set tsconfigRootDir in your parser options.
See: https://typescript-eslint.io/packages/parser/#tsconfigrootdir
要因
- モノレポで複数の
tsconfig.jsonが見つかり、@typescript-eslint/parserが、どの tsconfig を基準に解釈するか不明。 -
tsconfigRootDir未指定のためエラー。
対処法
web-react-01 および web-react-02 の eslint.config.js で、複数の tsconfig の中でどれを基準に解釈するかを明示。
import js from '@eslint/js'
import globals from 'globals'
import reactHooks from 'eslint-plugin-react-hooks'
import reactRefresh from 'eslint-plugin-react-refresh'
import tseslint from 'typescript-eslint'
import { defineConfig, globalIgnores } from 'eslint/config'
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
js.configs.recommended,
tseslint.configs.recommended,
reactHooks.configs['recommended-latest'],
reactRefresh.configs.vite,
],
languageOptions: {
ecmaVersion: 2020,
globals: globals.browser,
parser: tseslint.parser, // 追記
parserOptions: { // 追記
project: true, // 追記
tsconfigRootDir: import.meta.dirname // 追記
}
},
},
])
追加した各オプションについて
parser: tseslint.parser
- ESLint に TypeScript 用パーサを指定する設定。
- 以前は
parser: '@typescript-eslint/parser'だったかも。 - 標準の ESLint は JS 構文しか理解できないため、
typescript-eslintが提供する専用パーサ (@typescript-eslint/parser) を指定して TypeScript 構文(型注釈・インターフェースなど)を解釈できるようにする。 - 実際の処理:
-
- ESLint が
.ts/.tsxファイルを読み込む。
- ESLint が
-
tseslint.parserが内部で TypeScript Compiler API を呼び出して構文木を生成。 - ESLint のルールがその構文木を元に解析を行う。
-
parserOptions.project: true
- プロジェクトモードを有効化するフラグ。
-
trueを指定すると、現在ディレクトリ内のtsconfig.jsonを自動検出して、型情報を含む静的解析(typed lint)が行われる。 - https://typescript-eslint.io/packages/parser/#project
parserOptions.tsconfigRootDir: import.meta.dirname
- どのフォルダを基準に tsconfig.json を探すかを指定。
-
import.meta.dirnameは “この eslint.config.js があるディレクトリ” を意味する。- したがってモノレポ構成で
web-react-01/tsconfig.jsonおよびweb-react-02/tsconfig.jsonが存在する場合、それぞれのルートを確実に参照できる。
- したがってモノレポ構成で
- これが無いと、ESLint はワークスペース全体のどこか(親ディレクトリ)で
tsconfig.jsonを誤検出し、「プロジェクトを特定できない」エラーを出す。 - https://typescript-eslint.io/packages/parser/#tsconfigrootdir
