TypeScript tsconfig.json Configuration
tsconfig.json is the configuration file for a TypeScript project, used to specify compiler options and project settings.
Basic configuration
The most basic tsconfig.json file.
Example
{
"compilerOptions"
:
{
"target"
:
"ES2020"
,
"module"
:
"commonjs"
,
"strict"
:
true
,
"outDir"
:
"./dist"
}
,
"include"
:
[
"src/**/*"
]
,
"exclude"
:
[
"node_modules"
,
"dist"
]
}
Configuration notes:
- **target:** The target JavaScript version for compilation
- **module:** The module system to use
- **strict:** Enable all strict type checking
- **outDir:** The output directory
Compilation Target Version
Use target to specify the JavaScript version to compile to.
Example
// tsconfig.json
{
"compilerOptions"
:
{
// ES3, ES5, ES6/ES2015, ES2020, ESNext
"target"
:
"ES2020"
}
}
Output differences between different targets:
// target: ES5 - using var
var greeting = "Hello";
// target: ES2020 - using let/const
let greeting = "Hello";
Module System
Configure the module system.
Example
{
"compilerOptions"
:
{
"module"
:
"commonjs"
,
// Optional: none, commonjs, amd, umd, es6, es2020, esnext
}
}
Strict mode
The strict option enables all strict type checking.
Example
{
"compilerOptions"
:
{
"strict"
:
true
,
// Equivalent to enabling all of the following options:
// "strictNullChecks": true,
// "noImplicitAny": true,
// "strictFunctionTypes": true,
// etc.
}
}
Note:Always enable strict: true; this is a best practice.
Path Aliases
Configure path aliases to simplify imports.
Example
{
"compilerOptions"
:
{
"baseUrl"
:
"."
,
"paths"
:
{
"@/*"
:
[
"src/*"
]
,
"@components/*"
:
[
"src/components/*"
]
}
}
}
Usage:
import Button from "@components/Button";
import { Header } from "@/components";
File Inclusion and Exclusion
Control which files are included in compilation.
Example
{
"include"
:
[
"src/**/*"
]
,
"exclude"
:
[
"node_modules"
,
"dist"
,
"**/*.test.ts"
,
"**/*.spec.ts"
]
}
Overview of Common Compiler Options
| Option | Description |
|---|---|
| target | Compilation Target Version |
| module | Module System |
| strict | Strict mode |
| outDir | Output directory |
| rootDir | Root directory of source code |
| esModuleInterop | Allow ES module interoperability |
| skipLibCheck | Skip library checking |
| declaration | Generate .d.ts declaration files |
Summary
- **tsconfig.json:** TypeScript project configuration file
- **compilerOptions:** Core configuration for compiler options
- **include/exclude:** Control the file scope
- **Path aliases:** Simplify import paths
- **strict: true:** Always enable strict mode