Sub topic 5
Controlling Emitted Output
Assume you know basic TypeScript syntax, can run tsc from a terminal, and understand JSON configuration files. This chapter focuses on what TypeScript writes after it compiles your source files.
TypeScript can emit several kinds of output:
- JavaScript files for running the program.
- Source maps for debugging the original TypeScript.
- Declaration files that describe the public types of a package.
- Declaration maps that connect declaration files back to source files.
Choosing the output directory
Use outDir to keep generated files separate from your TypeScript source. Use rootDir to describe the source tree that should be mirrored inside the output directory.
Suppose your project contains src/main.ts. This configuration emits dist/main.js:
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"rootDir": "src",
"outDir": "dist",
"strict": true
},
"include": ["src"]
}The compiler preserves the relative directory structure. For example, src/utils/format.ts becomes dist/utils/format.js.
rootDir does not select files. The include, exclude, and files options select files. rootDir only controls how selected files map into outDir.
Generating source maps
A source map lets a debugger show the original TypeScript line while JavaScript runs. Enable it with sourceMap.
{
"compilerOptions": {
"outDir": "dist",
"sourceMap": true
}
}For src/main.ts, the compiler usually creates:
| Input | Generated file | Purpose |
|---|---|---|
| `src/main.ts` | `dist/main.js` | Runtime JavaScript |
| `src/main.ts` | `dist/main.js.map` | Mapping for debugging |
The generated JavaScript refers to its map file. Do not delete the .map files if you need useful stack traces or debugger locations.
Generating declaration files
Libraries often publish JavaScript together with .d.ts declaration files. A declaration file contains type information without implementation details.
Enable declarations with declaration:
{
"compilerOptions": {
"outDir": "dist",
"declaration": true,
"declarationMap": true
}
}A source file such as src/math.ts might produce:
dist/math.jsdist/math.d.tsdist/math.js.mapdist/math.d.ts.map
declarationMap helps editors navigate from a consumer's type information back to the original TypeScript source.
Building without emitting files
Use noEmit when another tool handles output or when you only want type-checking:
npx tsc --noEmitThis command reports type errors but does not write JavaScript, declarations, or source maps. It is useful in continuous integration and editor checks.
The output pipeline can therefore be summarized as follows:
Exercise
You want src/index.ts to compile to build/index.js, include debugger mappings, and produce type declarations. Which compiler options should you use?
Show answer
Set rootDir to "src", outDir to "build", sourceMap to true, and declaration to true.