一、tsconfig.json 简介

TypeScript 使用 tsconfig.json 文件作为其配置文件,当一个目录中存在 tsconfig.json 文件,则认为该目录为 TypeScript 项目的根目录。 通常 tsconfig.json 文件主要包含两部分内容:指定待编译文件定义编译选项

tsconfig.json 文件有以下几个顶层属性:

  • compileOnSave
  • compilerOptions ( compiler 编译的意思)
  • exclude
  • extends
  • files
  • include
  • references
  • typeAcquisition

二、初始化 tsconfig.json

在初始化操作,也有 2 种方式:

  1. 手动在项目根目录(或其他)创建 tsconfig.json 文件并填写配置;
  2. 通过 tsc --init 初始化 tsconfig.json 文件。

三、常见配置项

  1. {
  2. "compilerOptions": {
  3. "target": "ES5", // 目标语言的版本
  4. "module": "commonjs", // 指定生成代码的模板标准
  5. "noImplicitAny": true, // 不允许隐式的 any 类型
  6. "removeComments": true, // 删除注释
  7. "preserveConstEnums": true, // 保留 const enum 声明
  8. "sourceMap": true // 生成目标文件的sourceMap文件
  9. },
  10. "files": [ // 指定待编译文件
  11. "./src/index.ts"
  12. ]
  13. }

其中需要注意一点:
files 配置项值是一个数组,用来指定了待编译文件,即入口文件
当入口文件依赖其他文件时,不需要将被依赖文件也指定到 files 中,因为编译器会自动将所有的依赖文件归纳为编译对象,即 index.ts 依赖 user.ts 时,不需要在 files 中指定 user.tsuser.ts 会自动纳入待编译文件。

四、tsconfig.json 配置介绍

1. compileOnSave

compileOnSave 属性作用是设置保存文件的时候自动编译,但需要编译器支持

  1. {
  2. // ...
  3. "compileOnSave": false,
  4. }

2. compilerOptions

compilerOptions 属性作用是配置编译选项
编译选项配置非常繁杂,有很多配置,这里只列出常用的配置。

  1. {
  2. // ...
  3. "compilerOptions": {
  4. "incremental": true, // TS编译器在第一次编译之后会生成一个存储编译信息的文件,第二次编译会在第一次的基础上进行增量编译,可以提高编译的速度
  5. "tsBuildInfoFile": "./buildFile", // 增量编译文件的存储位置
  6. "diagnostics": true, // 打印诊断信息
  7. "target": "ES5", // 目标语言的版本
  8. "module": "CommonJS", // 生成代码的模板标准
  9. "outFile": "./app.js", // 将多个相互依赖的文件生成一个文件,可以用在AMD模块中,即开启时应设置"module": "AMD",
  10. "lib": ["DOM", "ES2015", "ScriptHost", "ES2019.Array"], // TS需要引用的库,即声明文件,es5 默认引用domes5scripthost,如需要使用es的高级版本特性,通常都需要配置,如es8的数组新特性需要引入"ES2019.Array",
  11. "allowJS": true, // 允许编译器编译JSJSX文件
  12. "checkJs": true, // 允许在JS文件中报错,通常与allowJS一起使用
  13. "outDir": "./dist", // 指定输出目录
  14. "rootDir": "./", // 指定输出文件目录(用于输出),用于控制输出目录结构
  15. "declaration": true, // 生成声明文件,开启后会自动生成声明文件
  16. "declarationDir": "./file", // 指定生成声明文件存放目录
  17. "emitDeclarationOnly": true, // 只生成声明文件,而不会生成js文件
  18. "sourceMap": true, // 生成目标文件的sourceMap文件
  19. "inlineSourceMap": true, // 生成目标文件的inline SourceMapinline SourceMap会包含在生成的js文件中
  20. "declarationMap": true, // 为声明文件生成sourceMap
  21. "typeRoots": [], // 声明文件目录,默认是node_modules/@types
  22. "types": [], // 加载的声明文件包
  23. "removeComments":true, // 删除注释
  24. "noEmit": true, // 不输出文件,即编译后不会生成任何js文件
  25. "noEmitOnError": true, // 发送错误时不输出任何文件
  26. "noEmitHelpers": true, // 不生成helper函数,减小体积,需要额外安装,常配合importHelpers一起使用
  27. "importHelpers": true, // 通过tslib引入helper函数,文件必须是模块
  28. "downlevelIteration": true, // 降级遍历器实现,如果目标源是es3/5,那么遍历器会有降级的实现
  29. "strict": true, // 开启所有严格的类型检查
  30. "alwaysStrict": true, // 在代码中注入'use strict'
  31. "noImplicitAny": true, // 不允许隐式的any类型
  32. "strictNullChecks": true, // 不允许把nullundefined赋值给其他类型的变量
  33. "strictFunctionTypes": true, // 不允许函数参数双向协变
  34. "strictPropertyInitialization": true, // 类的实例属性必须初始化
  35. "strictBindCallApply": true, // 严格的bind/call/apply检查
  36. "noImplicitThis": true, // 不允许this有隐式的any类型
  37. "noUnusedLocals": true, // 检查只声明、未使用的局部变量(只提示不报错)
  38. "noUnusedParameters": true, // 检查未使用的函数参数(只提示不报错)
  39. "noFallthroughCasesInSwitch": true, // 防止switch语句贯穿(即如果没有break语句后面不会执行)
  40. "noImplicitReturns": true, //每个分支都会有返回值
  41. "esModuleInterop": true, // 允许export=导出,由import from 导入
  42. "allowUmdGlobalAccess": true, // 允许在模块中全局变量的方式访问umd模块
  43. "moduleResolution": "node", // 模块解析策略,ts默认用node的解析策略,即相对的方式导入
  44. "baseUrl": "./", // 解析非相对模块的基地址,默认是当前目录
  45. "paths": { // 路径映射,相对于baseUrl
  46. // 如使用jq时不想使用默认版本,而需要手动指定版本,可进行如下配置
  47. "jquery": ["node_modules/jquery/dist/jquery.min.js"]
  48. },
  49. "rootDirs": ["src","out"], // 将多个目录放在一个虚拟目录下,用于运行时,即编译后引入文件的位置可能发生变化,这也设置可以虚拟srcout在同一个目录下,不用再去改变路径也不会报错
  50. "listEmittedFiles": true, // 打印输出文件
  51. "listFiles": true // 打印编译的文件(包括引用的声明文件)
  52. }
  53. }

3. exclude

exclude 属性作用是指定编译器需要排除的文件或文件夹。
默认排除 node_modules 文件夹下文件。

  1. {
  2. // ...
  3. "exclude": [
  4. "src/lib" // 排除src目录下的lib文件夹下的文件不会编译
  5. ]
  6. }

include 属性一样,支持 glob 通配符:

  • * 匹配0或多个字符(不包括目录分隔符)
  • ? 匹配一个任意字符(不包括目录分隔符)
  • **/ 递归匹配任意子目录

4. extends

extends 属性作用是引入其他配置文件,继承配置
默认包含当前目录和子目录下所有 TypeScript 文件。

  1. {
  2. // ...
  3. // 把基础配置抽离成tsconfig.base.json文件,然后引入
  4. "extends": "./tsconfig.base.json"
  5. }

5. files

files 属性作用是指定需要编译的单个文件列表
默认包含当前目录和子目录下所有 TypeScript 文件。

  1. {
  2. // ...
  3. "files": [
  4. // 指定编译文件是src目录下的leo.ts文件
  5. "scr/leo.ts"
  6. ]
  7. }

6. include

include 属性作用是指定编译需要编译的文件或目录

  1. {
  2. // ...
  3. "include": [
  4. // "scr" // 会编译src目录下的所有文件,包括子目录
  5. // "scr/*" // 只会编译scr一级目录下的文件
  6. "scr/*/*" // 只会编译scr二级目录下的文件
  7. ]
  8. }

7. references

references 属性作用是指定工程引用依赖。
在项目开发中,有时候我们为了方便将前端项目和后端node项目放在同一个目录下开发,两个项目依赖同一个配置文件和通用文件,但我们希望前后端项目进行灵活的分别打包,那么我们可以进行如下配置:

  1. {
  2. // ...
  3. "references": [ // 指定依赖的工程
  4. {"path": "./common"}
  5. ]
  6. }

8. typeAcquisition

typeAcquisition 属性作用是设置自动引入库类型定义文件(.d.ts)相关。
包含 3 个子属性:

  • enable : 布尔类型,是否开启自动引入库类型定义文件(.d.ts),默认为 false;
  • include : 数组类型,允许自动引入的库名,如:[“jquery”, “lodash”];
  • exculde : 数组类型,排除的库名。
  1. {
  2. // ...
  3. "typeAcquisition": {
  4. "enable": false,
  5. "exclude": ["jquery"],
  6. "include": ["jest"]
  7. }
  8. }

五、常见配置示例

1. 移除代码中注释

  1. {
  2. "compilerOptions": {
  3. "removeComments": true,
  4. }
  5. }

编译前:

  1. // 返回当前版本号
  2. function getVersion(version:string = "1.0.0"): string{
  3. return version;
  4. }
  5. console.log(getVersion("1.0.1"))

编译结果:

  1. function getVersion(version) {
  2. if (version === void 0) { version = "1.0.0"; }
  3. return version;
  4. }
  5. console.log(getVersion("1.0.1"));

2. 开启null、undefined检测

tsconfig.json:

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

修改 index.ts 文件内容:

  1. const leo;
  2. leo = new Pingan('leo','hello');

这时候编辑器也会提示错误信息,执行 tsc 后,控制台报错:

  1. src/index.ts:9:11 - error TS2304: Cannot find name 'Pingan'.
  2. 9 leo = new Pingan('leo','hello');
  3. Found 1 error.

3. 配置复用

通过 extends 属性实现配置复用,即一个配置文件可以继承另一个文件的配置属性。
比如,建立一个基础的配置文件 configs/base.json

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

tsconfig.json 就可以引用这个文件的配置了:

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

4. 生成枚举的映射代码

在默认情况下,使用 const 修饰符后,枚举不会生成映射代码。
如下,我们可以看出:使用 const 修饰符后,编译器不会生成任何 RequestMethod 枚举的任何映射代码,在其他地方使用时,内联每个成员的值,节省很大开销。

  1. const enum RequestMethod {
  2. Get,
  3. Post,
  4. Put,
  5. Delete
  6. }
  7. let methods = [
  8. RequestMethod.Get,
  9. RequestMethod.Post
  10. ]

编译结果:

  1. "use strict";
  2. let methods = [
  3. 0 /* Get */,
  4. 1 /* Post */
  5. ];

当然,我们希望生成映射代码时,也可以设置 tsconfig.json 中的配置,设置 preserveConstEnums 编译器选项为 true

  1. {
  2. "compilerOptions": {
  3. "target": "es5",
  4. "preserveConstEnums": true
  5. }
  6. }

最后编译结果变成:

  1. "use strict";
  2. var RequestMethod;
  3. (function (RequestMethod) {
  4. RequestMethod[RequestMethod["Get"] = 0] = "Get";
  5. RequestMethod[RequestMethod["Post"] = 1] = "Post";
  6. RequestMethod[RequestMethod["Put"] = 2] = "Put";
  7. RequestMethod[RequestMethod["Delete"] = 3] = "Delete";
  8. })(RequestMethod || (RequestMethod = {}));
  9. let methods = [
  10. 0 /* Get */,
  11. 1 /* Post */
  12. ];

5. 关闭 this 类型注解提示

通过下面代码编译后会报错:

  1. const button = document.querySelector("button");
  2. button?.addEventListener("click", handleClick);
  3. function handleClick(this) {
  4. console.log("Clicked!");
  5. this.removeEventListener("click", handleClick);
  6. }

报错内容:

  1. src/index.ts:10:22 - error TS7006: Parameter 'this' implicitly has an 'any' type.
  2. 10 function handleClick(this) {
  3. Found 1 error.

这是因为 this 隐式具有 any 类型,如果没有指定类型注解,编译器会提示“”this” 隐式具有类型 “any”,因为它没有类型注释。”。

解决方法有2种:

  1. 指定 this 类型,如本代码中为 HTMLElement 类型:

HTMLElement 接口表示所有的 HTML 元素。一些HTML元素直接实现了 HTMLElement 接口,其它的间接实现HTMLElement接口。

  1. 使用 --noImplicitThis 配置项:

在 TS2.0 还增加一个新的编译选项: --noImplicitThis,表示当 this 表达式值为 any 类型时生成一个错误信息。我们设置为 true 后就能正常编译。

  1. {
  2. "compilerOptions": {
  3. "noImplicitThis": true
  4. }
  5. }

六、Webpack/React 中使用示例

1. 配置编译 ES6 代码,JSX 文件

创建测试项目 webpack-demo,结构如下:

  1. webpack-demo/
  2. |- package.json
  3. |- tsconfig.json
  4. |- webpack.config.js
  5. |- /dist
  6. |- bundle.js
  7. |- index.html
  8. |- /src
  9. |- index.js
  10. |- index.ts
  11. |- /node_modules

安装 TypeScript 和 ts-loader:

  1. $ npm install --save-dev typescript ts-loader

配置 tsconfig.json,支持 JSX,并将 TypeScript 编译为 ES5:

  1. {
  2. "compilerOptions": {
  3. "outDir": "./dist/",
  4. "noImplicitAny": true,
  5. + "module": "es6",
  6. + "target": "es5",
  7. + "jsx": "react",
  8. "allowJs": true
  9. }
  10. }

还需要配置 webpack.config.js,使其能够处理 TypeScript 代码,这里主要在 rules 中添加 ts-loader

  1. const path = require('path');
  2. module.exports = {
  3. entry: './src/index.ts',
  4. module: {
  5. rules: [
  6. {
  7. test: /\.tsx?$/,
  8. use: 'ts-loader',
  9. exclude: /node_modules/
  10. }
  11. ]
  12. },
  13. resolve: {
  14. extensions: [ '.tsx', '.ts', '.js' ]
  15. },
  16. output: {
  17. filename: 'bundle.js',
  18. path: path.resolve(__dirname, 'dist')
  19. }
  20. };

2. 配置 source map

想要启用 source map,我们必须配置 TypeScript,以将内联的 source map 输出到编译后的 JavaScript 文件中。
只需要在 tsconfig.json 中配置 sourceMap 属性:

  1. {
  2. "compilerOptions": {
  3. "outDir": "./dist/",
  4. + "sourceMap": true,
  5. "noImplicitAny": true,
  6. "module": "commonjs",
  7. "target": "es5",
  8. "jsx": "react",
  9. "allowJs": true
  10. }
  11. }

然后配置 webpack.config.js 文件,让 webpack 提取 source map,并内联到最终的 bundle 中:

  1. const path = require('path');
  2. module.exports = {
  3. entry: './src/index.ts',
  4. + devtool: 'inline-source-map',
  5. module: {
  6. rules: [
  7. {
  8. test: /\.tsx?$/,
  9. use: 'ts-loader',
  10. exclude: /node_modules/
  11. }
  12. ]
  13. },
  14. resolve: {
  15. extensions: [ '.tsx', '.ts', '.js' ]
  16. },
  17. output: {
  18. filename: 'bundle.js',
  19. path: path.resolve(__dirname, 'dist')
  20. }
  21. };
  1. {
  2. "compilerOptions": {
  3. /* 基本选项 */
  4. "target": "es5", // 指定 ECMAScript 目标版本: 'ES3' (default), 'ES5', 'ES6'/'ES2015', 'ES2016', 'ES2017', or 'ESNEXT'
  5. "module": "commonjs", // 指定使用模块: 'commonjs', 'amd', 'system', 'umd' or 'es2015'
  6. "lib": [], // 指定要包含在编译中的库文件
  7. "allowJs": true, // 允许编译 javascript 文件
  8. "checkJs": true, // 报告 javascript 文件中的错误
  9. "jsx": "preserve", // 指定 jsx 代码的生成: 'preserve', 'react-native', or 'react'
  10. "declaration": true, // 生成相应的 '.d.ts' 文件
  11. "sourceMap": true, // 生成相应的 '.map' 文件
  12. "outFile": "./", // 将输出文件合并为一个文件
  13. "outDir": "./", // 指定输出目录
  14. "rootDir": "./", // 用来控制输出目录结构 --outDir.
  15. "removeComments": true, // 删除编译后的所有的注释
  16. "noEmit": true, // 不生成输出文件
  17. "importHelpers": true, // tslib 导入辅助工具函数
  18. "isolatedModules": true, // 将每个文件作为单独的模块 (与 'ts.transpileModule' 类似).
  19. /* 严格的类型检查选项 */
  20. "strict": true, // 启用所有严格类型检查选项
  21. "noImplicitAny": true, // 在表达式和声明上有隐含的 any类型时报错
  22. "strictNullChecks": true, // 启用严格的 null 检查
  23. "noImplicitThis": true, // this 表达式值为 any 类型的时候,生成一个错误
  24. "alwaysStrict": true, // 以严格模式检查每个模块,并在每个文件里加入 'use strict'
  25. /* 额外的检查 */
  26. "noUnusedLocals": true, // 有未使用的变量时,抛出错误
  27. "noUnusedParameters": true, // 有未使用的参数时,抛出错误
  28. "noImplicitReturns": true, // 并不是所有函数里的代码都有返回值时,抛出错误
  29. "noFallthroughCasesInSwitch": true, // 报告 switch 语句的 fallthrough 错误。(即,不允许 switch case 语句贯穿)
  30. /* 模块解析选项 */
  31. "moduleResolution": "node", // 选择模块解析策略: 'node' (Node.js) or 'classic' (TypeScript pre-1.6)
  32. "baseUrl": "./", // 用于解析非相对模块名称的基目录
  33. "paths": {}, // 模块名到基于 baseUrl 的路径映射的列表
  34. "rootDirs": [], // 根文件夹列表,其组合内容表示项目运行时的结构内容
  35. "typeRoots": [], // 包含类型声明的文件列表
  36. "types": [], // 需要包含的类型声明文件名列表
  37. "allowSyntheticDefaultImports": true, // 允许从没有设置默认导出的模块中默认导入。
  38. /* Source Map Options */
  39. "sourceRoot": "./", // 指定调试器应该找到 TypeScript 文件而不是源文件的位置
  40. "mapRoot": "./", // 指定调试器应该找到映射文件而不是生成文件的位置
  41. "inlineSourceMap": true, // 生成单个 soucemaps 文件,而不是将 sourcemaps 生成不同的文件
  42. "inlineSources": true, // 将代码与 sourcemaps 生成到一个文件中,要求同时设置了 --inlineSourceMap --sourceMap 属性
  43. /* 其他选项 */
  44. "experimentalDecorators": true, // 启用装饰器
  45. "emitDecoratorMetadata": true // 为装饰器提供元数据的支持
  46. }
  47. }