Course contentsShow
← TypeScript
Lesson 1119 of 1,79626. Modules in TypeScriptFree lesson

rootDirs for Virtual Directory Merging

Treating multiple source folders as a single logical root for imports.

rootDirs for Virtual Directory Merging

What you'll learn: How to make TypeScript treat multiple physical source directories as a single logical root for import resolution.

The Problem: Split Source Locations

Sometimes your TypeScript project has source files scattered across multiple directories that you want to treat as if they were in the same folder. This commonly happens when:

  • You have generated code in one directory and handwritten code in another
  • Your build process outputs files to a different location
  • You're working with internationalization where different locales live in separate folders

Without help, TypeScript requires you to use relative paths like ../../generated/types to import from these separate locations — messy and brittle.

What rootDirs Does

The rootDirs compiler option in tsconfig.json tells TypeScript to treat multiple directories as if they're merged into a single virtual directory structure. When resolving imports, TypeScript searches all specified root directories as if their contents were combined.

Think of it like overlaying multiple transparent sheets on a projector — TypeScript sees them as one unified image.

Configuration Example

{
  "compilerOptions": {
    "rootDirs": [
      "src",
      "generated"
    ]
  }
}

With this configuration, a file in src/utils.ts can import from generated/types.ts using just import { Type } from './types' — as if both files were in the same directory.

When to Use rootDirs

Use rootDirs when you have multiple source directories that logically represent the same namespace but are physically separate. It's particularly useful for build pipelines where code generation or preprocessing creates parallel directory structures.

Key Takeaway: rootDirs allows TypeScript to resolve imports across multiple directories as if they were merged into one logical location, simplifying import paths in split-source scenarios.