LoginSignup
9
3

More than 3 years have passed since last update.

[TypeScript] error TS6059: File is not under 'rootDir'. の対処法

Last updated at Posted at 2019-09-05

表題のエラーに関して、詰まりましたのでメモを残しておきます。

症状

error TS6059: File '.ts' is not under 'rootDir' '**'. 'rootDir' is expected to contain all source files.

TypeScriptのtscコマンド実行時に、上記のエラーが発生します。

環境

▼package.json

"typescript": "^3.6.2"

症状が発生するミニマムな設定は以下の通りです。

▼tsconfig.json

{
  "compilerOptions": {
    "outDir": "./output",
    "rootDir": "./source"
  }
}

この環境で、./sourceディレクトリ以外の場所に.tsという拡張子を持つファイルが存在すると表題のエラーが発生します。
この.tsファイルはTypeScriptファイルでなくとも、ファイル名に含まれているだけでエラーが発生します。jestのテスト用ファイルや動画ファイルの拡張子にも反応します。

原因

この症状は、tscコマンドが実行されたディレクトリ以下のすべてのファイルを検索するために発生します。
rootDirオプションはtscコマンドのファイル検索範囲を制限しません。
このオプションはoutDirにファイルを出力する際、ディレクトリ構成を維持するためだけに使用されます。

参考リンク : tsc should not care and fail with ts files outside of rootDir

直感的にはrootDirという設定があれば、そのほかのファイルはすべて無視するような気がしますが、tscコマンドはそのようには振る舞いません。

対策

解決策として、tsconfig.jsonにrootDirincludeの両方のオプションを設定します。

▼tsconfig.json

{
  "compilerOptions": {
    "outDir": "./output",
    "rootDir": "./source",
                 ^^^^^^^
  },
  "include": ["source"]
               ^^^^^^^
}

参考リンク : tsc should not care and fail with ts files outside of rootDir

includeを使用することで、明示的に検索対象ディレクトリをtscコマンドに教えられます。
この設定により、includeディレクトリ以外のファイルは無視されるようになります。

以上、ありがとうございました。

9
3
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
9
3