Stephen Fong
Stephen Fong

Reputation: 837

tsconfig.json difference between include and rootDir

From the documentation it's said that include specifies an array of filenames or patterns to include in the program (i.e. in the compilation process). Similarly, rootDir is the path to the folder with the source code of the app to be included in the compilation process.

  "include": ["./src/"],
  "exclude": ["node_modules/*", "test/*"],
  "compilerOptions": {
    "module": "commonjs",
    "target": "es2015",
    "rootDir": "./src",
    "outDir": "./dist/",
  }

What's their difference then?

Upvotes: 20

Views: 14248

Answers (1)

Capi Etheriel
Capi Etheriel

Reputation: 3640

The include top-level option defines files that will be included. It is relative to .tsconfig.json and defaults to **, meaning all files in the project. Files outside include will not be compiled.

The compilerOptions.rootDir option defines the root of the tree at outDir. By default, it uses the common path among the included folders. This means in a project with two files src/services/user.ts and src/services/auth.ts, rootDir would default to src/services/ (ie., the longest common path segments of all input files). The output directory would look like this:

dist
├── auth.js
└── user.js

Manually setting rootDir to src would instead produce this output directory:

dist
└── services
    ├── auth.js
    └── user.js

Finally, having files outside of rootDir included by the include option would emit an error:

error TS6059: File '~/project/outside.ts' is not under 'rootDir' '~/project/src'. 'rootDir' is expected to contain all source files.
  The file is in the program because:
    Matched by include pattern '**/*' in '~/project/tsconfig.json'

Upvotes: 27

Related Questions