位置:首页 > TypeScript > TypeScript tsconfig.json 常用配置详解与优化指南

TypeScript tsconfig.json 常用配置详解与优化指南

时间:2026-08-15  |  作者:极客少年  |  阅读:0

tsconfig.json 可以理解为 TypeScript 项目的“总配置文件”,主要用来定义编译选项,以及整个项目的相关设置。

TypeScript tsconfig.json 配置

基本配置

最基础的 tsconfig.json 文件如下。

实例

{
    "compilerOptions": {
        "target": "ES2020",
        "module": "commonjs",
        "strict": true,
        "outDir": "./dist"
    },
    "include": ["src/**/*"],
    "exclude": ["node_modules", "dist"]
}

配置说明

  • target:编译目标 Ja vaScript 版本
  • module:使用的模块系统
  • strict:启用所有严格类型检查
  • outDir:输出目录

编译目标版本

通过 target,可以明确指定最终要编译成哪个版本的 Ja vaScript。

实例

// tsconfig.json
{
    "compilerOptions": {
        // ES3, ES5, ES6/ES2015, ES2020, ESNext
        "target": "ES2020"
    }
}

不同目标的输出差异

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

模块系统

通过 module 配置模块化方案。

实例

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

严格模式

strict 选项用于启用所有严格类型检查。

实例

{
    "compilerOptions": {
        "strict": true,
        // 等同于开启以下所有选项:
        // "strictNullChecks": true,
        // "noImplicitAny": true,
        // "strictFunctionTypes": true,
        // 等等
    }
}

建议:始终启用 strict: true,这是最佳实践。

路径别名

可以通过路径别名简化导入。

实例

{
    "compilerOptions": {
        "baseUrl": ".",
        "paths": {
            "@/*": ["src/*"],
            "@components/*": ["src/components/*"]
        }
    }
}

使用方式

import Button from "@components/Button";
import { Header } from "@/components";

文件包含与排除

通过 include 和 exclude,可以控制哪些文件参与编译。

实例

{
    "include": ["src/**/*"],
    "exclude": [
        "node_modules",
        "dist",
        "**/*.test.ts",
        "**/*.spec.ts"
    ]
}

常用编译选项一览

选项 说明
target 编译目标版本
module 模块系统
strict 严格模式
outDir 输出目录
rootDir 源码根目录
esModuleInterop 允许 ES 模块互操作
skipLibCheck 跳过库检查
declaration 生成 .d.ts 声明文件

总结

  • tsconfig.json:TypeScript 项目配置文件
  • compilerOptions:编译选项核心配置
  • include/exclude:控制文件范围
  • 路径别名:简化导入路径
  • strict: true:始终启用严格模式

免责声明:文中图文均来自网络,如有侵权请联系删除,心愿游戏发布此文仅为传递信息,不代表心愿游戏认同其观点或证实其描述。

相关文章

更多

精选合集

更多

大家都在玩

热门话题

大家都在看

更多