Sub topic 3
Checking too much: finding unintended files and type packages
This chapter assumes you can read a tsconfig.json, run tsc from the command line, and use npx. It also assumes you have a baseline from --extendedDiagnostics, which the previous chapter covered. Here you will find out whether the compiler is checking more files than you intended, and why.
Why program scope matters
The compiler builds a program before it checks anything. A program is the full set of source files and declaration files that tsc loads for one run. Every file in that set is parsed and bound. Every file that is not a declaration file (.d.ts) is also checked, and declaration files are checked unless skipLibCheck is on.
Time in the parse, bind, and check phases grows with the size of the program. If your project has 400 files of your own code and the program contains 6,000 files, most of your time goes to files you never wrote. The cause is often an accident, not a hard problem in your types.
The Files line in --extendedDiagnostics output is your first signal. A small project that reports thousands of files deserves a closer look.
Three ways files enter a program
A file joins the program in one of three ways.
- Root files. These come from the
filesandincludeoptions intsconfig.json, minus anything matched byexclude. - Imports and references. Any file reachable through
import,require,/// <reference path>, or/// <reference types>is added, even ifincludedid not list it. - Automatic type packages. Packages under
node_modules/@typesare loaded as global types unless thetypesoption says otherwise.
Most surprises come from the second and third paths. They also explain why changing exclude often does nothing.
Count the files in your own program
Use --listFilesOnly to print every file the program contains, without checking anything. Filtering out node_modules leaves the files from your own repository.
npx tsc --noEmit --listFilesOnly | grep -v node_modules | wc -l
npx tsc --noEmit --explainFiles > explain.txtThe first command prints one number. Compare it with the number of source files you expect. If you expected about 400 and see 1,800, something is pulling in extra files.
The second command writes explain.txt. For each file, --explainFiles prints the reason it is in the program. The output looks like this:
src/index.ts
Matched by include pattern 'src' in 'tsconfig.json'
node_modules/@types/node/index.d.ts
Entry point for implicit type library 'node'
src/generated/schema.ts
Imported via "./generated/schema" from file 'src/api.ts'The reasons you will meet most often are:
| Reason text | What it means |
|---|---|
| Matched by include pattern | A root file from `include`. |
| Root file specified for compilation | A root file from `files`. |
| Imported via "..." from file "..." | Another file imports it. |
| Entry point for implicit type library | Loaded automatically from `@types`. |
| Library referenced via "..." from file "..." | A `/// <reference types>` directive or a package's type dependency. |
| Type library referenced via "..." | A package listed in `types`. |
Read explain.txt from the top of the list of your own files. Search for directories you did not expect, such as dist, build, coverage, scripts, or test fixtures. Then read the reason for each one. The reason tells you which include pattern or which importing file is responsible.
Common causes of extra files
An `include` that is too wide
If tsconfig.json has no include or files, the compiler uses all TypeScript files in the directory and its subdirectories. That includes tests, scripts, and tooling configuration. Set include explicitly:
{
"include": ["src"]
}Note that when exclude is not set, it defaults to node_modules, bower_components, jspm_packages, and the outDir. If you set exclude yourself, those defaults no longer apply, so list node_modules again if you still need it excluded.
Build output inside the include path
If outDir is dist and your include is ["."], the compiler can pick up dist/**/*.d.ts on a later run. The default exclude covers outDir, but a custom exclude can remove that protection. Output files then get parsed and checked as sources.
A barrel file that imports everything
A barrel file is an index.ts that re-exports many modules. Importing one name from it loads all of the modules it re-exports, because the compiler has to resolve the whole file. A large barrel on a hot import path can put hundreds of files into every program that touches it. In explain.txt, look for one index.ts that is the importer of many files.
Importing a package's whole type surface
Some packages ship large declaration trees. Importing from a package root can load far more .d.ts files than a deep import of the one module you need. Count the node_modules files too:
npx tsc --noEmit --listFilesOnly | grep node_modules | wc -lThen group them by package to find the largest one:
npx tsc --noEmit --listFilesOnly | grep node_modules \
| sed -E 's#.*/node_modules/((@[^/]+/)?[^/]+)/.*#\1#' \
| sort | uniq -c | sort -rn | headThe sed expression extracts the package name, including the scope for names like @types/node. The command prints the ten packages that contribute the most files. A package you rarely use that appears at the top is a candidate for investigation.
Unintended type packages
By default, TypeScript includes every visible package under node_modules/@types in the global scope. You do not have to import them. This is convenient for @types/node, but it means that every @types/* package installed anywhere up the directory tree is loaded.
This often goes wrong in three ways.
- A monorepo hoists many
@types/*packages to the rootnode_modules. Every package in the repository then loads all of them. - A transitive dependency installs an
@typespackage you never asked for, such as@types/jestnext to@types/mocha. Both declare globals likedescribe, which can also cause conflicting-declaration errors. - A frontend project loads
@types/node, which brings in Node globals that do not exist in the browser.
The types option restricts the automatic loading to the packages you list:
{
"compilerOptions": {
"types": ["node"]
},
"include": ["src"]
}With this setting, only @types/node is loaded automatically. Other @types packages are still found when your code imports a module that they describe. For example, import express from "express" still resolves @types/express. Only the automatic global inclusion stops.
An empty array, "types": [], loads no global type packages at all. That is a good starting point for a library that uses no globals. Add packages back one at a time when the compiler reports missing names such as process, describe, or Buffer.
Finding what was loaded automatically
In explain.txt, search for the phrase implicit type library:
grep -B1 "implicit type library" explain.txtEach hit is a package that loaded only because types was not set. If you see packages you do not use, you have found savings.
A worked example
Suppose a repository reports these numbers from --extendedDiagnostics:
Files: 4,812
Check time: 21.40sThe project has about 300 source files. You run the counting command from earlier. It reports 1,150 files outside node_modules, so something added about 850 files of your own code. You then search explain.txt and find that most of them are in dist/types, reached by the reason Matched by include pattern '.' in 'tsconfig.json'. The include is ["."] and a custom exclude removed the default for outDir.
You fix it in two steps.
{
"compilerOptions": {
"outDir": "dist",
"noEmit": false,
"types": ["node"]
},
"include": ["src"],
"exclude": ["dist", "node_modules"]
}Narrowing include to src removes the build output from the roots. Listing dist in exclude is a second safeguard. Setting types stops 40 unrelated @types packages from loading. After the change, the Files line drops, and the check time falls with it. Always rerun --extendedDiagnostics and compare, since file counts and time do not always move together.
The program scope as a flow
The flow below shows how the three entry paths feed one program, and where exclude and types apply.
Limits of this approach
Reducing the program does not help if the time goes to expensive types in your own files. If the file count is reasonable and the check time is still high, move on to the trace tools in later chapters.
Two cautions apply.
- Narrowing
includecan exclude files that an editor or a test runner expects in the same project. If editor support breaks in a test folder, give tests their owntsconfigthat extends the main one. - Setting
typeschanges what type-checks, not only how fast it runs. Run your normal build and tests after the change.
Exercises
Exercise
A project sets "exclude": ["scripts"], but --explainFiles still lists scripts/seed.ts with the reason Imported via "../scripts/seed" from file 'src/db.ts'. Why is the file still in the program, and what are two ways to remove it?
Show answer
exclude only filters root files found through include. The import in src/db.ts adds the file independently. To remove it, either stop importing it from src/db.ts (move the shared code into src), or, if the import is only needed for tests or tooling, move that import out of the production entry path. Changing exclude alone has no effect.
Exercise
You set "types": ["node"] and the compiler now reports "Cannot find name 'describe'" in your test files. What does this error tell you, and how do you fix it without giving up the option?
Show answer
Before the change, a test framework's @types package, such as @types/jest, loaded automatically and declared describe. With types set, only the listed packages load as globals. Add the framework to the list, for example "types": ["node", "jest"], or put tests in a separate tsconfig that lists the test types.
Exercise
Write the commands to count files in your own program and to list which automatic type libraries were loaded.
Show answer
npx tsc --noEmit --listFilesOnly | grep -v node_modules | wc -l counts your own files. npx tsc --noEmit --explainFiles > explain.txt followed by grep -B1 "implicit type library" explain.txt shows the automatic type libraries and the files that follow them.