Sub topic 2
Choosing Which Files Are Compiled
Assume you know basic TypeScript syntax, JSON, and how to run npx tsc from a Node.js project. This chapter explains how TypeScript decides which files belong to a compilation.
How TypeScript finds the configuration
The TypeScript compiler is usually run with:
npx tscWithout a file argument, tsc searches the current directory and its parent directories for tsconfig.json. That file defines the project settings, including the source files to read.
A typical project might look like this:
project/
├── src/
│ ├── index.ts
│ └── math.ts
├── scripts/
│ └── generate.ts
├── tests/
│ └── math.test.ts
├── dist/
└── tsconfig.jsonYou normally compile src, but you may want to leave scripts, tests, and generated dist files out of the main build.
Using `include`
The include option selects files with glob patterns. A glob is a pattern that can match multiple paths.
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"rootDir": "src",
"outDir": "dist",
"strict": true
},
"include": ["src"]
}When a directory is listed, TypeScript searches it recursively for supported files, such as .ts, .tsx, and .d.ts. The src setting therefore includes both src/index.ts and src/math.ts.
You can use more specific patterns:
{
"include": ["src/**/*.ts", "types/**/*.d.ts"]
}The ** pattern matches any number of directory levels. The * pattern matches part of one filename or directory name.
Using `exclude`
The exclude option removes files from the results of include.
{
"include": ["src", "tests"],
"exclude": ["src/legacy", "tests/fixtures", "node_modules", "dist"]
}This includes most files under src and tests, except files in the listed directories.
exclude is not a security boundary. A file can still enter the compilation if an included file imports it. For example, if src/index.ts imports ../scripts/generate, TypeScript may include that imported file even when scripts appears in exclude.
Using `files`
The files option lists exact files:
{
"compilerOptions": {
"strict": true
},
"files": ["src/index.ts", "src/environment.d.ts"]
}This is useful for a small project or for explicitly including a global declaration file. It is less convenient for a growing application because every new source file must be added manually.
You generally choose either files for precise control or include with exclude for directory-based projects.
Seeing the selected files
Use --listFiles to inspect the compilation:
npx tsc --listFiles --noEmitThe output includes your source files and the declaration files for built-in JavaScript libraries. If an unexpected file appears, check imports as well as your include and exclude patterns.
Exercise
A project uses "include": ["src"] and "exclude": ["src/generated"]. An included file imports src/generated/api.ts. Will api.ts necessarily stay excluded?
Show answer
No. An imported file can still enter the compilation. Check the import graph when debugging unexpected files.