Sub topic 1
What tsconfig.json does and how tsc finds it
Prerequisites
You should know basic TypeScript syntax, including type annotations and interfaces. You should also be able to run commands with Node.js and npm installed. This chapter assumes you know basic JSON syntax.
The role of tsconfig.json
tsconfig.json is the configuration file for the TypeScript compiler. The compiler, usually run with the tsc command, reads this file to determine:
- Which TypeScript files belong to the project
- Which JavaScript version to generate
- Which module format to use
- Which type-checking rules to apply
- Whether to emit JavaScript, declaration files, or source maps
- Where generated files should be written
A configuration file is useful because the same settings apply every time the project is checked or built.
A minimal project might have this structure:
my-project/
├── src/
│ └── index.ts
├── package.json
└── tsconfig.jsonThe tsconfig.json file can contain settings such as these:
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"outDir": "dist",
"rootDir": "src",
"strict": true
},
"include": ["src"]
}The compilerOptions object controls compiler behavior. The include property selects files using patterns. Here, TypeScript includes files under the src directory.
How tsc chooses a configuration
When you run tsc without input filenames, TypeScript looks for a tsconfig.json in the current directory. If it does not find one there, it searches parent directories.
npx tscFor example, if your terminal is in my-project/src, TypeScript can find my-project/tsconfig.json by searching upward.
You can select a specific configuration with --project, also written as -p:
npx tsc --project ./tsconfig.jsonYou can also provide a directory. TypeScript then looks for tsconfig.json in that directory:
npx tsc -p ./packages/apiThis is useful in a repository with several packages and several configuration files.
A command that names source files behaves differently:
npx tsc src/index.tsWhen you provide input files directly, TypeScript does not use the project configuration in the usual way. Compiler options can instead be supplied on the command line. For project builds, prefer tsc or tsc -p.
What belongs in the project
The include, exclude, and files properties control file selection. These settings affect which files TypeScript starts with. Imported files can also become part of the program because TypeScript follows imports.
include is convenient for directory-based projects:
{
"include": ["src/**/*.ts"],
"exclude": ["node_modules", "dist"]
}files is explicit and lists each file:
{
"files": ["src/index.ts", "src/config.ts"]
}Use files for a small, tightly controlled project. Use include when new source files should be discovered automatically.
Exercise
Exercise
Which command explicitly tells TypeScript to use the configuration in packages/web/tsconfig.json?
Show answer
npx tsc -p packages/web/tsconfig.json