生成 tsconfig.json:表面之下隐藏着什么?

面向初学者的在线Python训练器

轻松学习Python,无需理论负担。在浏览器中直接解决带自动检查的实践任务,无需安装任何东西。

开始课程

引言:为什么 tsconfig.json 不仅仅是一个文件?



每个写过 TypeScript 的人都曾遇到过神秘的 tsconfig.json 文件。如果你是新手,很可能只是从文档中复制它,或者搜索“如何生成 tsconfig.json”。而如果你是有经验的开发者——或许你曾思考过:当我运行 tsc --init 时,底层究竟发生了什么?



在本文中,我们不仅会给出现成的方案,还会深入 TypeScript 编译器的“机舱”。你将了解编译器如何读取配置,哪些标志控制代码的严格性,以及如何临时编写自己的最小化 tsconfig.json“生成器”。开始吧!



1. 什么是 tsconfig.json,为什么需要它?



tsconfig.json 是一个 JSON 文件,它告诉 TypeScript 编译器 (tsc) 具体如何处理你的代码。没有它,tsc 将以“默认”模式运行,但对于严肃的项目来说,这通常不够。



在底层,tsconfig.json 定义了:

  • 要编译哪些文件(键 include、exclude、files)。
  • 输出结果存放位置(键 outDir)。
  • 要支持的 JavaScript 版本(键 target)。
  • 类型检查的严格程度(键 strict、noImplicitAny 等)。
  • 额外的模块和路径。


当你问“how can I generate a tsconfig.json file”时,答案通常是:tsc --init。但让我们弄清楚这个命令到底生成了什么。



2. tsc --init 命令:底层发生了什么?



在终端中运行:

npx tsc --init


项目根目录下会出现一个 tsconfig.json 文件,其中包含大量被注释掉的设置。实际上,在底层,TypeScript 编译器执行以下算法:



  1. 检查当前目录中是否已存在 tsconfig.json。
  2. 如果不存在——则创建一个包含默认设置的模板。
  3. 设置 target: "es2016"、module: "commonjs"、strict: true 以及其他合理的值。
  4. 所有其他选项都被注释掉,以便开发者在需要时取消注释。


但如果你想要自定义生成呢?例如,立即启用严格模式或设置输出文件的路径?为此,你可以编写自己的脚本。



2.1. 示例:用 TypeScript 编写自己的 tsconfig.json 生成器



假设你正在编写一个用于自动配置项目的工具。下面是一个在底层生成 tsconfig.json 的函数示例:



import * as fs from 'fs';import * as path from 'path';

interface TsConfig { compilerOptions: { target: string; module: string; strict: boolean; outDir: string; rootDir: string; esModuleInterop: boolean; skipLibCheck: boolean; forceConsistentCasingInFileNames: boolean; }; include: string[]; exclude: string[];}

function generateTsConfig( target: string = 'ES2020', outDir: string = './dist', rootDir: string = './src', strict: boolean = true): TsConfig { return { compilerOptions: { target, module: 'commonjs', strict, outDir, rootDir, esModuleInterop: true, skipLibCheck: true, forceConsistentCasingInFileNames: true, }, include: ['src/**/*'], exclude: ['node_modules', 'dist'], };}

// 生成并保存const config = generateTsConfig();fs.writeFileSync( path.join(process.cwd(), 'tsconfig.json'), JSON.stringify(config, null, 2));console.log('tsconfig.json 已创建!');

博客

书籍推荐