tsconfig.json和tsconfig.node.json和tsconfig.app.json有什么区别

发布于:2025-03-28 ⋅ 阅读:(21) ⋅ 点赞:(0)

TypeScript 配置文件区别解析

在 TypeScript 项目中,常见的配置文件有 tsconfig.jsontsconfig.node.json 和 tsconfig.app.json,它们各自有不同的用途和配置范围。

1. 主配置文件 tsconfig.json

作用:这是 TypeScript 项目的主要配置文件,包含项目的基本编译设置。

特点

  • 通常位于项目根目录

  • 包含项目通用的 TypeScript 编译选项

  • 可以作为其他配置文件的基准(通过 extends 继承)

典型配置

json

复制

{
  "compilerOptions": {
    "target": "ESNext",
    "module": "ESNext",
    "strict": true,
    "jsx": "preserve",
    "moduleResolution": "node",
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true,
    "baseUrl": ".",
    "paths": {
      "@/*": ["src/*"]
    }
  },
  "include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.tsx", "src/**/*.vue"],
  "exclude": ["node_modules"]
}

2. Node 环境配置 tsconfig.node.json

作用:专门用于 Node.js 环境下的 TypeScript 配置。

使用场景

  • 配置 Vite/Webpack 等构建工具的配置文件类型检查

  • 后端 Node.js 服务代码的编译配置

  • 工具脚本的编译配置

特点

  • 继承自主 tsconfig.json

  • 调整模块系统和目标环境为 Node.js 适用

  • 通常包含 vite.config.ts 等构建配置文件的类型检查

典型配置

json

复制

{
  "extends": "@tsconfig/node16/tsconfig.json",
  "compilerOptions": {
    "composite": true,
    "module": "CommonJS",
    "moduleResolution": "node",
    "types": ["node"]
  },
  "include": ["vite.config.ts", "scripts/**/*.ts"]
}

3. 应用配置 tsconfig.app.json

作用:专门用于前端应用代码的 TypeScript 配置。

使用场景

  • 前端业务代码的编译配置

  • 浏览器环境下的类型检查

  • Vue/React 等前端框架的组件代码

特点

  • 继承自主 tsconfig.json

  • 针对浏览器环境优化

  • 包含前端框架特定的类型支持

典型配置

json

复制

{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "jsx": "preserve",
    "types": ["vite/client"],
    "paths": {
      "@/*": ["src/*"]
    }
  },
  "include": ["src/**/*.ts", "src/**/*.tsx", "src/**/*.vue"],
  "exclude": ["node_modules"]
}

配置文件关系图

复制

tsconfig.json (基础配置)
├── tsconfig.node.json (Node环境配置)
└── tsconfig.app.json (前端应用配置)

为什么需要多个配置?

  1. 环境差异:Node.js 和浏览器环境有不同的模块系统和全局变量

  2. 构建工具需求:Vite/Webpack 配置需要 CommonJS 模块,而前端代码通常用 ESM

  3. 类型检查范围:工具脚本和业务代码可能有不同的类型要求

  4. 性能优化:可以针对不同部分只检查相关文件,加快编译速度

实际项目中的使用

在 Vite + Vue 项目中,典型的配置方式是:

  • tsconfig.json: 基础共享配置

  • tsconfig.node.json: 检查 vite.config.ts 等构建配置文件

  • tsconfig.app.json: 检查 src/ 目录下的前端代码

这样分离可以确保每种类型的代码都获得最适合的类型检查和编译设置。