tsconfig.json(译)

原文地址

tsconfig.json文件通常放在工程根目录下,用来定义编译的配置。

使用

  • 不提供任何输入文件的配置,直接调用tsccompiler会找tsconfig.json,从当前文件夹开始,找不到就往父目录找。
  • 不提供任何输入文件的配置,使用—project或者-p,调用tsc,指定一个包含tsconfig.json文件的文件夹路径,或者一个包含配置信息的合法.json文件的路径。

如果指定了输入文件,那么tsconfig.json文件会被忽略。

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
// 使用 file
{
"compilerOptions": {
"module": "commonjs",
"noImplicitAny": true,
"removeComments": true,
"preserveConstEnums": true,
"sourceMap": true
},
"files": [
"core.ts",
"sys.ts",
"types.ts",
"scanner.ts",
"parser.ts",
"utilities.ts",
"binder.ts",
"checker.ts"
]
}

// 使用 include 和 exclude
{
"compilerOptions": {
"module": "system",
"noImplicitAny": true,
"removeComments": true,
"preserveConstEnums": true,
"outFile": "../../built/local/tsc.js",
"sourceMap": true
},
"include": [
"src/**/*"
],
"exclude": [
"node_modules",
"**/*.spec.ts"
]
}

细节

compilerOptions可以忽略,compiler会使用默认配置。Compiler Options

files接收一组相对/绝对路径。include/exclude接受一组glob-like file pattern。支持的glob通配符如下:

  • *匹配0或多个字符(除了文件夹分隔符)
  • ?匹配任意1个字符(除了文件夹分隔符)
  • **/递归匹配任意子目录

如果某glob pattern只包含*/.*,那么默认包含的文件为所有扩展名为.ts/.tsx/.d.ts的文件。(如果allowJstrue,那么扩展名为.js/.jsx的文件也被包含在内)

如果files/include都没有指定值,那么compiler默认包含文件夹/子文件夹下的所有TypeScript文件。(扩展名为.ts/.tsx/.d.ts的文件。如果allowJstrue,那么扩展名为.js/.jsx的文件也被包含在内)

exclude可以过滤掉include指定的文件,但不能过滤掉files指定的文件。如果exclude没有指定值,默认包含node_modules/bower_components/jspm_packages/<outDir>

被包含的文件引用的文件,也被包含在内,不会被exclude过滤掉,除非引用它的文件被过滤掉了。

compiler会过滤掉那些可能成为输出文件的输入文件。例如,同一目录下同时有[name].ts/[name].d.ts/[name].js,那么[name].d.ts/[name].js会被忽略。

tsconfig.json可以是一个空文件,compiler会使用默认配置。

@typestypeRootstypes

默认情况下,只有@types目录下的包会被包含在compilation里。例如,./node_modules/@types/../node_modules/@types/../../node_modules/@types

如果指定了typeRoots的值,那么只有typeRoots目录下的包会被包含进来。

例如:

1
2
3
4
5
{
"compilerOptions": {
"typeRoots": ["./typings"]
}
}

只有./typings目录下的包会被包含进来,./node_modules/@types目录下的包不会被包含进来。

如果指定了types的值,那么只有列举出来的包会被包含进来。

1
2
3
4
5
{
"compilerOptions": {
"types": ["node", "lodash", "express"]
}
}

只有./node_modules/@types/node/./node_modules/@types/lodash/./node_modules/@types/express会被包含进来,其它./node_modules/@types/*目录下的包不会被包含进来。

指定types值为[],将会自动过滤所有@types包。

使用extends继承配置文件

例如:

configs/base.json

1
2
3
4
5
6
{
"compilerOptions": {
"noImplicitAny": true,
"strictNullChecks": true
}
}

tsconfig.json

1
2
3
4
5
6
7
{
"extends": "./configs/base",
"files": [
"main.ts",
"supplemental.ts"
]
}

tsconfig.nostrictnull.json

1
2
3
4
5
6
{
"extends": "./configs/base",
"compilerOptions": {
"strictNullChecks": false
}
}

compileOnSave

告诉IDE,在保存文件的时候使用给定的tsconfig.json处理所有的文件。

1
2
3
4
5
6
{
"compileOnSave": true,
"compilerOptions": {
"noImplicitAny": true
}
}

Schema