TypeScript tsconfig.json Configuration

tsconfig.json is the configuration file for TypeScript projects, 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 Description:

  • target:Target JavaScript version to compile to
  • module:Module system to use
  • strict:Enable all strict type checks
  • outDir: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 for different targets:

// target: ES5 - 使用 var
var greeting = "Hello";

// target: ES2020 - 使用 let/const
let greeting = "Hello";

Module System

Configure the modularization scheme.

Example

{
    "compilerOptions": {
        "module": "commonjs",
        // Options: none, commonjs, amd, umd, es6, es2020, esnext
    }
}

Strict Mode

The strict option enables all strict type checks.

Example

{
    "compilerOptions": {
        "strict": true,
        // Equivalent to enabling all of the following options:
        // "strictNullChecks": true,
        // "noImplicitAny": true,
        // "strictFunctionTypes": true,
        // etc.
    }
}

Recommendation: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"
    ]
}

Common Compiler Options Overview

Option Description
target Compilation Target Version
module Module System
strict Strict Mode
outDir Output Directory
rootDir Source Root Directory
esModuleInterop Allow ES Module Interoperability
skipLibCheck Skip Library Check
declaration Generate .d.ts Declaration Files

Summary

  • tsconfig.json:TypeScript project configuration file
  • compilerOptions:Core configuration of compiler options
  • include/exclude:Control file scope
  • Path aliases:Simplify import paths
  • strict: true:Always enable strict mode
Other Extensions