Last updated: Feb 28, 2024
Reading time·2 min
The "File is not under 'rootDir'" error occurs when we try to import something
from a file that is not located under the specified rootDir
in
tsconfig.json
.
To solve the error, move the file under the project's root directory or remove
the rootDir
setting from tsconfig.json
.
Assume we have a project with the following folder structure.
typescript └──src └── index.ts └── another-file.ts
And the rootDir option in my
tsconfig.json file points to the
src
directory.
{ "compilerOptions": { "rootDir": "src", // ... rest } }
If I try to import from another-file.ts
in my index.ts
file, I would get the
error, because another-file.ts
is not located in the src
directory of my
project.
// ⛔️ Error: File '/home/borislav/Desktop/typescript/another-file.ts' // is not under 'rootDir' '/home/borislav/Desktop/typescript/src'. // 'rootDir' is expected to contain all source files.ts(6059) import { Sizes } from '../another-file'; console.log(Sizes);
We are trying to import from a file that is located 1 directory up (outside our
specified rootDir
).
rootDir
folderOne way to solve the error is to move the file under your specified rootDir
and import it.
typescript └──src └── index.ts └── another-file.ts
Now I can import the file without getting any errors.
import { Sizes } from './another-file'; // 👇️ { Small: 'S', Medium: 'M', Large: 'L' } console.log(Sizes);
Here is the example code for another-file.ts
.
export enum Sizes { Small = 'S', Medium = 'M', Large = 'L', }
I've also written an article on how to import values from another file in TS.
rootDir
optionIf you have to stick to the previous file structure of:
typescript └──src └── index.ts └──another-file.ts
You can try to remove the rootDir
option from your tsconfig.json
.
The rootDir
setting defaults to the largest common path of all non-declaration
input files.
Remove the rootDir
option from your tsconfig.json
file.
{ "compilerOptions": { // "rootDir": "src", // 👈️ remove this // ... rest } }
Now the TypeScript compiler will automatically determine the rootDir
setting
for your project by following your imports.
// ✅ Works fine now import { Sizes } from '../another-file'; // 👇️ { Small: 'S', Medium: 'M', Large: 'L' } console.log(Sizes);
If I rerun my build command I can see that my build
folder has the following
structure now.
typescript └── build └── src └── index.js └── another-file.js
Notice that TypeScript kept the same directory structure inside of the build
directory after it compiled the files.
You can learn more about the related topics by checking out the following tutorials: