TypeScript tsconfig.json 配置
1. 解释
一个项目可以通过以下方式之一来编译:
2. tsconfig.json 主要配置项
{
"compilerOptions": {},
"files": [],
"include": [],
"exclude": [],
"extends": "",
"compileOnSave": false,
"typeAcquisition": {}
}
2.1 compilerOptions
下面是一份梳理的常用 compilerOptions 属性配置:
{
"compilerOptions": {
"target": "esnext", /* 指定编译之后的版本目标: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'. */
"module": "esnext", /* 指定要使用的模块标准: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
"noImplicitAny": false, /* 是否默认禁用 any */
"removeComments": true, /* 是否移除注释 */
"declaration": true, /* 是否自动创建类型声明文件 */
"strict": true, /* 启动所有类型检查 */
"jsx": "preserve", /* 指定jsx代码用于的开发环境 */
"importHelpers": true, /* 引入tslib里的辅助工具函数*/
"moduleResolution": "node", /* 选择模块解析策略,有'node'和'classic'两种类型 */
"experimentalDecorators": true, /* 启用实验性的装饰器特性 */
"esModuleInterop": true, /* 通过为导入内容创建命名空间,实现Commonjs和ES模块之间的互操作性 */
"allowSyntheticDefaultImports": true, /* 允许从没有默认导出的模块中默认导入 */
"sourceMap": true, /* 是否生成map文件 */
"baseUrl": ".", /* 工作根目录 */
"types": [ /* 指定引入的类型声明文件,默认是自动引入所有声明文件,一旦指定该选项,则会禁用自动引入,改为只引入指定的类型声明文件,如果指定空数组[]则不引用任何文件 */
"webpack-env",
"jest"
],
"paths": { /* 指定模块的路径,和 baseUrl有关联,和 webpack 中 resolve.alias 配置一样 */
"@/*": [
"src/*"
]
},
"lib": [ /* 译过程中需要引入的库文件的列表 */
"esnext",
"dom",
"dom.iterable",
"scripthost"
]
}
}
2.2 files,include 和 exclude
glob
通配符有:
如果 "files"
和 "include"
都没有被指定,编译器默认包含当前目录和子目录下所有的 TypeScript 文件(.ts
, .d.ts
和 .tsx
),排除在"exclude"
里指定的文件。
如果开启了 allowJs
选项,那 .js
和 .jsx
文件也属于编译器包含范围。
{
"files": [
"core.ts",
"index.ts",
"types.ts"
],
"exclude": [
"node_modules",
"lib",
"**/*.test.ts"
],
"include": [
"src/**/*"
],
}
如果没有特殊指定,"exclude"
默认情况下会排除 node_modules,bower_components,jspm_packages
和 <outDir>
目录。
优先级:命令行配置 > files > exclude > include
2.3 extends
{
"extends": "config/base.json"
}
configs/base.json
:
{
"compilerOptions": {
"noImplicitAny": true,
"strictnullchecks": true
}
}
需要注意:
2.4 compileOnSave
2.5 typeAcquisition
3. @types,typeRoots 和 types
但是如果指定了 typeRoots
,则只有 typeRoots
路径下的包才会被包含进来:
{
"compilerOptions": {
"typeRoots" : ["./typings"]
}
}
这个配置文件会包含所有 ./typings
下面的包,而不包含 ./node_modules/@types
里面的包。
如果指定了 types
,只有被列出来的包才会被包含进来。比如:
{
"compilerOptions": {
"types": ["node", "lodash", "express"]
}
}
{
"compilerOptions": {
"types": []
}
}
注意,自动引入只在你使用了全局的声明(相反于模块)时是重要的。如果你使用 import "foo"
语句,TypeScript 仍然会查找 node_modules
和node_modules/@types
文件夹来获取 foo
包。