Sub topic 7
The compiler options you need first
This chapter assumes you can already compile a file with npx tsc and that a tsconfig.json exists in your project, as covered in the previous chapters. You should also know how import and export work in JavaScript modules, and how a Node project's package.json is laid out.
A freshly generated tsconfig.json lists dozens of options. You can ignore most of them for now. Five options decide where tsc reads from, what JavaScript it writes, and where that JavaScript goes: target, module, rootDir, outDir, and include. The chapter after this one covers strict on its own.
The working model
tsc answers four questions each time it runs:
- Which files are part of the program? (
include,exclude,files) - Which language features may the output use? (
target) - Which module system does the output use? (
module) - Where does each output file go? (
rootDir,outDir)
The rest of this chapter takes the options in that order.
A project to experiment with
Use the ts-demo project from earlier chapters, or create this layout:
ts-demo/
package.json
tsconfig.json
src/
index.ts
util/
math.tssrc/util/math.ts:
export function add(a: number, b: number): number {
return a + b;
}src/index.ts:
import { add } from "./util/math";
console.log(add(2, 3));tsconfig.json:
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"rootDir": "src",
"outDir": "dist",
"strict": true,
"skipLibCheck": true
},
"include": ["src"]
}Run it:
npx tsc
node dist/index.jsThe output is 5. The compiler wrote dist/index.js and dist/util/math.js. The folder structure under src was copied under dist. The sections below explain why.
include, exclude, and files: choosing the input
include is a list of paths or glob patterns, relative to the folder that holds tsconfig.json. The wildcards are:
*matches any characters in one path segment, except the folder separator.?matches exactly one character.**/matches any number of nested folders.
A pattern with no file extension, such as "src", means "every supported file under this folder". That is the same as "src/**/*". Supported files are .ts, .tsx, and .d.ts. .js files are added only when allowJs is on.
exclude removes files from the set that include selected. files lists individual files with no wildcards, which suits very small projects.
Three behaviors cause most of the confusion:
- If you write no
includeand nofiles,tsctakes every supported file in the config's folder and its subfolders. That often includes tests, scripts, and build tooling you did not mean to compile. - If you write no
exclude, the default isnode_modules,bower_components,jspm_packages, and youroutDir. If you write your ownexclude, you replace that list. Add"dist"yourself, ortscmay read its own output on the next run. excludeonly filters whatincludefound. A file excluded by pattern is still compiled if an included file imports it.
To see which files the compiler actually picked up, run:
npx tsc --listFilesOnlyThis prints every file in the program, including files from node_modules/@types, and writes nothing.
target: which JavaScript syntax the output may use
target sets the version of the JavaScript language that the emitted code is allowed to use. Syntax newer than the target is rewritten into older equivalents. Older syntax is left alone.
With this source:
interface User {
address?: { city: string };
}
export function cityOf(user: User): string {
return user.address?.city ?? "unknown";
}"target": "ES2022" emits the ?. and ?? operators unchanged, because Node 16 and later runs them natively. "target": "ES2019" rewrites them into longer chains of === null and === void 0 checks, because those operators arrived in ES2020.
Keep two limits in mind:
targetchanges syntax only. It does not add missing runtime features. If you compile[1, 2, 3].at(-1)for an engine that lacksArray.prototype.at,tscdoes not supply it. You need a polyfill or a newer runtime.targetalso sets the default forlib, the built-in type declarations. Withtarget: "ES2022", the compiler knows aboutArray.prototype.atandObject.hasOwnin types.
Pick the target from the oldest runtime you must support. For a Node service, check your Node version and choose the matching ES edition. ES2022 suits current Node LTS releases. For browser code that a bundler processes, the bundler usually lowers syntax further, so the target there is mostly about what you let the bundler see.
module: which import style the output uses
module controls how import and export statements are written in the output. The values you meet most often are:
| Value | Output | Typical use |
|---|---|---|
| `NodeNext` | ES modules or CommonJS, chosen per file by the nearest `package.json` | Code that Node runs directly |
| `CommonJS` | `require` and `module.exports` | Older Node projects |
| `ESNext` | `import` and `export` left as written | Code that a bundler processes |
NodeNext follows Node's own rules. A .ts file in a package with "type": "module" becomes an ES module. In a package with no type or "type": "commonjs", which is what npm init -y gives you, it becomes CommonJS. That is why the demo above ran with node dist/index.js: the emitted index.js uses require.
NodeNext also changes how imports are resolved, and one rule catches many people. In an ES module package, relative imports must include the file extension, and you write the extension of the output file:
import { add } from "./util/math.js";You write .js even though the file on disk is math.ts. The compiler maps it to the TypeScript source, and Node later finds the real math.js. Without the extension, you get an error that asks if you meant ./util/math.js. In a CommonJS package, the extension is optional.
When a bundler such as esbuild, Vite, or webpack processes your code, the usual pairing is "module": "ESNext" with "moduleResolution": "Bundler". Resolution is the lookup that turns an import path into a file. NodeNext sets it for you. For other module values you may need to set moduleResolution yourself.
rootDir and outDir: where output goes
outDir is the folder that receives emitted files. rootDir is the folder that corresponds to the top of that output. The output path of each file is:
outDir + (source path relative to rootDir) + new extensionWith rootDir: "src" and outDir: "dist", the file src/util/math.ts becomes dist/util/math.js.
If you leave rootDir unset, the compiler infers it as the longest folder path shared by all input files. That inference is the source of a classic surprise. Suppose your include covers src and a tests folder. The shared folder is the project root, so the output becomes dist/src/index.js and dist/tests/a.test.js. If you later delete the tests, the shared folder becomes src, and the output moves to dist/index.js. A script that runs node dist/index.js then breaks without any change to its own files.
Setting rootDir explicitly fixes the layout. It also gives you an error when a file falls outside it:
error TS6059: File '/home/me/ts-demo/tests/a.test.ts' is not under 'rootDir' '/home/me/ts-demo/src'.That error is useful. It tells you your include and rootDir disagree. Either narrow include, or move the tests to a separate tsconfig that has its own rootDir.
Common mistakes
| Symptom | Likely cause | Fix |
|---|---|---|
| Output appears at `dist/src/index.js` | `rootDir` unset and inputs from more than one top folder | Set `rootDir: "src"` and narrow `include` |
| `TS6059` about `rootDir` | An included file is outside `rootDir` | Move the file or change `include` |
| `Cannot use import statement outside a module` at runtime | Output is ESM but `package.json` has no `"type": "module"`, or the reverse | Make `module` and the package `type` agree |
| Relative import fails to resolve under `NodeNext` | Missing `.js` extension in an ES module package | Write `"./file.js"` |
| `tsc` slows down or reads old output | Custom `exclude` dropped the default `outDir` exclusion | Add the output folder to `exclude` |
| `Property 'at' does not exist` | `target` or `lib` too old for that API | Raise `target` or add the right `lib` entry |
Checking what the compiler decided
You do not have to guess how options combine. Print the final configuration, with defaults filled in:
npx tsc --showConfigThis shows the resolved compilerOptions, plus the exact list of files that include produced. Run it whenever the output location or the file set surprises you.
Exercise
Your project has src/index.ts and scripts/seed.ts. Your tsconfig has "outDir": "dist", no rootDir, and "include": ["src", "scripts"]. Where does tsc write the output for src/index.ts? What two changes would make it write dist/index.js while still compiling only src?
Show answer
With no rootDir, the inferred root is the common parent of src and scripts, which is the project folder. The output goes to dist/src/index.js. To get dist/index.js, change include to ["src"] and set "rootDir": "src". Then scripts/seed.ts is no longer part of the program, and the root is fixed no matter what else changes.
Exercise
A teammate sets "module": "NodeNext" in a package whose package.json has "type": "module". Their import import { add } from "./util/math" is rejected. Why, and what is the fix?
Show answer
In an ES module package under NodeNext, relative imports need an explicit file extension. The compiler expects the output extension, so the fix is import { add } from "./util/math.js", even though the source file is math.ts.