$ cd /path/to/project
$ npm init -y
$ npm i typescript -D
$ npx tsc --init
Created a new tsconfig.json with:
target: es2016
module: commonjs
strict: true
esModuleInterop: true
skipLibCheck: true
forceConsistentCasingInFileNames: true
You can learn more at https://aka.ms/tsconfig
一、简介
tsconfig.json
是 TypeScript 编译器的配置文件,用于指定编译 TypeScript 代码时的编译选项和编译目标等信息。通过修改该文件,可以定制 TypeScript 编译器的行为,例如指定编译目标、启用或禁用特定的语言特性、设置代码检查规则等。1.1 与 jsconfig.json 的关系
jsconfig.json
源自tsconfig.json
,默认启用了一些与 JavaScript 相关的编译选项,常用于 JavaScript 项目。可以简单理解为设置了allowJs
为true
的tsconfig.json
。比如,当我们使用 Webpack Alias 时,可以往
jsconfig.json
里添加baseUrl
、paths
配置以获得路径智能提示,提高开发体验。1.2 创建 tsconfig.json
方式有二。一是利用
tsc --init
命令添加(详见)。二是手动添加,然后参考 TSConfig bases,借鉴各种框架的配置示例,也可直接安装对应
@tsconfig/xxx
包并使用extends
继承配置。1.3 选择编译配置
通常,若目录下存在
tsconfig.json
文件,则表示该目录是 TypeScript 项目的根目录。尽管如此,在用法上还是要注意。以上三种方式,编译时的配置稍有不同:
如果你是刚接触,可参考 TSConfig bases 选择适合你所用框架的配置。
1.4 配置优先级
CLI Options > 项目 tsconfig.json 配置 > 默认配置
二、配置选项
tsconfig.json 里配置选项很多,超过 100 个。
2.1 顶级选项(Root Fields)
顶级选项有这几个:
还包括 Vue.js 中会用到的 vueCompilerOptions 选项等。
2.1.1 compileOnSave
启用该选项,可以让 IDE/Editor 在保存文件时自动编译。
请注意,它(目前)并没有得到 Visual Studio Code 的支持。仅在 Visual Studio 2015 和安装了 atom-typescript 插件的 Atom 中得到了支持。而该插件和 Atom 均已停止维护。
2.1.2 compileerOptions
该选项是 TypeScript 配置的重头戏,下文再详细介绍。
2.1.3 files
该选项用于指定待编译的文件,接受一个字符串数组,可以是相对路径或绝对路径,但不能是 Glob 模式。
注意点:
2.1.4 include
该选项类似于
files
字段,同样用于指定编译器应该包含哪些文件进行编译,未指定时默认编译根目录下所有 TypeScript 文件。区别在于,include
支持 Glob 模式来指定文件路径。include
和exclude
支持 Glob 模式如下:若 Glob 模式未指定文件扩展名时,默认支持
.ts
、.tsx
和.d.ts
。若allowJs
为true
,还包括.js
和.jsx
。2.1.5 exclude
该选项用于指定
include
里面需要忽略的文件。exclude 的默认值为["node_modules", "bower_components", "jspm_packages"]
,但排除文件还包括outDir
指定值。以下示例将会忽略的文件为
["node_modules", "bower_components", "jspm_packages", "dist"]
。2.1.6 files、include 和 exclude 的关系
未完待续...
Related Link