首页/文章/typescript

详解TypeScript项目中的tsconfig.json配置

2022-11-29
4682 分钟
...

在TS的项目中,TS最终都会被编译JS文件执行,TS编译器在编译TS文件的时候都会先在项目根目录的tsconfig.json文件,根据该文件的配置进行编译,默认情况下,如果该文件没有任何配置,TS编译器会默认编译项目目录下所有的.ts、.tsx、.d.ts文件。实际项目中,会根据自己的需求进行自定义的配置,下面就来详细了解下tsconfig.json的文件配置。

文件选项配置

  • files : 表示编译需要编译的单个文件列表

    "files": [
      // 指定编译文件是src目录下的a.ts文件
      "scr/a.ts"
    ] 
  • include: 表示编译需要编译的文件或目录

    "include": [
      // "scr" // 会编译src目录下的所有文件,包括子目录
      // "scr/*" // 只会编译scr一级目录下的文件
      "scr/*/*" // 只会编译scr二级目录下的文件
    ] 
  • exclude:表示编译器需要排除的文件或文件夹

    默认排除node_modules文件夹下文件

    "exclude": [
      // 排除src目录下的lib文件夹下的文件不会编译
      "src/lib"
    ] 
  • extends: 引入其他配置文件,继承配置

    // 把基础配置抽离成tsconfig.base.json文件,然后引入
    "extends": "./tsconfig.base.json" 
  • compileOnSave:设置保存文件的时候自动编译

    vscode暂不支持该功能,可以使用’Atom’编辑器

    "compileOnSave": true 

编译选项配置

  • compilerOptions:配置编译选项

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

    "compilerOptions": {
      "incremental": true, // TS编译器在第一次编译之后会生成一个存储编译信息的文件,第二次编译会在第一次的基础上进行增量编译,可以提高编译的速度
      "tsBuildInfoFile": "./buildFile", // 增量编译文件的存储位置
      "diagnostics": true, // 打印诊断信息 
      "target": "ES5", // 目标语言的版本
      "module": "CommonJS", // 生成代码的模板标准
      "outFile": "./app.js", // 将多个相互依赖的文件生成一个文件,可以用在AMD模块中,即开启时应设置"module": "AMD",
      "lib": ["DOM", "ES2015", "ScriptHost", "ES2019.Array"], // TS需要引用的库,即声明文件,es5 默认引用dom、es5、scripthost,如需要使用es的高级版本特性,通常都需要配置,如es8的数组新特性需要引入"ES2019.Array",
      "allowJS": true, // 允许编译器编译JS,JSX文件
      "checkJs": true, // 允许在JS文件中报错,通常与allowJS一起使用
      "outDir": "./dist", // 指定输出目录
      "rootDir": "./", // 指定输出文件目录(用于输出),用于控制输出目录结构
      "declaration": true, // 生成声明文件,开启后会自动生成声明文件
      "declarationDir": "./file", // 指定生成声明文件存放目录
      "emitDeclarationOnly": true, // 只生成声明文件,而不会生成js文件
      "sourceMap": true, // 生成目标文件的sourceMap文件
      "inlineSourceMap": true, // 生成目标文件的inline SourceMap,inline SourceMap会包含在生成的js文件中
      "declarationMap": true, // 为声明文件生成sourceMap
      "typeRoots": [], // 声明文件目录,默认时node_modules/@types
      "types": [], // 加载的声明文件包
      "removeComments":true, // 删除注释 
      "noEmit": true, // 不输出文件,即编译后不会生成任何js文件
      "noEmitOnError": true, // 发送错误时不输出任何文件
      "noEmitHelpers": true, // 不生成helper函数,减小体积,需要额外安装,常配合importHelpers一起使用
      "importHelpers": true, // 通过tslib引入helper函数,文件必须是模块
      "downlevelIteration": true, // 降级遍历器实现,如果目标源是es3/5,那么遍历器会有降级的实现
      "strict": true, // 开启所有严格的类型检查
      "alwaysStrict": true, // 在代码中注入'use strict'
      "noImplicitAny": true, // 不允许隐式的any类型
      "strictNullChecks": true, // 不允许把null、undefined赋值给其他类型的变量
      "strictFunctionTypes": true, // 不允许函数参数双向协变
      "strictPropertyInitialization": true, // 类的实例属性必须初始化
      "strictBindCallApply": true, // 严格的bind/call/apply检查
      "noImplicitThis": true, // 不允许this有隐式的any类型
      "noUnusedLocals": true, // 检查只声明、未使用的局部变量(只提示不报错)
      "noUnusedParameters": true, // 检查未使用的函数参数(只提示不报错)
      "noFallthroughCasesInSwitch": true, // 防止switch语句贯穿(即如果没有break语句后面不会执行)
      "noImplicitReturns": true, //每个分支都会有返回值
      "esModuleInterop": true, // 允许export=导出,由import from 导入
      "allowUmdGlobalAccess": true, // 允许在模块中全局变量的方式访问umd模块
      "moduleResolution": "node", // 模块解析策略,ts默认用node的解析策略,即相对的方式导入
      "baseUrl": "./", // 解析非相对模块的基地址,默认是当前目录
      "paths": { // 路径映射,相对于baseUrl
        // 如使用jq时不想使用默认版本,而需要手动指定版本,可进行如下配置
        "jquery": ["node_modules/jquery/dist/jquery.min.js"]
      },
      "rootDirs": ["src","out"], // 将多个目录放在一个虚拟目录下,用于运行时,即编译后引入文件的位置可能发生变化,这也设置可以虚拟src和out在同一个目录下,不用再去改变路径也不会报错
      "listEmittedFiles": true, // 打印输出文件
      "listFiles": true// 打印编译的文件(包括引用的声明文件)
    } 
{
  "compilerOptions": {
    /* Basic Options */
    "target": "ES2017", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */
    "module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
    // "lib": [],                             /* Specify library files to be included in the compilation. */
    // "allowJs": true,                       /* Allow javascript files to be compiled. */
    // "checkJs": true,                       /* Report errors in .js files. */
    // "jsx": "preserve",                     /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
    // "declaration": true,                   /* Generates corresponding '.d.ts' file. */
    // "declarationMap": true,                /* Generates a sourcemap for each corresponding '.d.ts' file. */
    "sourceMap": true,                     /* Generates corresponding '.map' file. */
    // "outFile": "./",                       /* Concatenate and emit output to single file. */
    "outDir": "./dist",                        /* Redirect output structure to the directory. */
    // "rootDir": "./",                       /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
    // "composite": true,                     /* Enable project compilation */
    // "removeComments": true,                /* Do not emit comments to output. */
    // "noEmit": true,                        /* Do not emit outputs. */
    // "importHelpers": true,                 /* Import emit helpers from 'tslib'. */
    // "downlevelIteration": true,            /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
    // "isolatedModules": true,               /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
    /* Strict Type-Checking Options */
    "strict": true, /* Enable all strict type-checking options. */
    // "noImplicitAny": true,                 /* Raise error on expressions and declarations with an implied 'any' type. */
    // "strictNullChecks": true,              /* Enable strict null checks. */
    // "strictFunctionTypes": true,           /* Enable strict checking of function types. */
    // "strictPropertyInitialization": true,  /* Enable strict checking of property initialization in classes. */
    // "noImplicitThis": true,                /* Raise error on 'this' expressions with an implied 'any' type. */
    // "alwaysStrict": true,                  /* Parse in strict mode and emit "use strict" for each source file. */
    /* Additional Checks */
    // "noUnusedLocals": true,                /* Report errors on unused locals. */
    // "noUnusedParameters": true,            /* Report errors on unused parameters. */
    // "noImplicitReturns": true,             /* Report error when not all code paths in function return a value. */
    // "noFallthroughCasesInSwitch": true,    /* Report errors for fallthrough cases in switch statement. */
    /* Module Resolution Options */
    // "moduleResolution": "node",            /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
    // "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
    // "paths": {
    //   "src/*": ["src/*"],
    // }, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
    // "rootDirs": [],                        /* List of root folders whose combined content represents the structure of the project at runtime. */
    "typeRoots": ["./node_modules/@types", "./src/types"],                       /* List of folders to include type definitions from. */
    // "types": [],                           /* Type declaration files to be included in compilation. */
    // "allowSyntheticDefaultImports": true,  /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
    "esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
    // "preserveSymlinks": true,              /* Do not resolve the real path of symlinks. */
    /* Source Map Options */
    // "sourceRoot": "",                      /* Specify the location where debugger should locate TypeScript files instead of source locations. */
    // "mapRoot": "",                         /* Specify the location where debugger should locate map files instead of generated locations. */
    // "inlineSourceMap": true,               /* Emit a single file with source maps instead of having a separate file. */
    // "inlineSources": true,                 /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
    /* Experimental Options */
    // "experimentalDecorators": true,        /* Enables experimental support for ES7 decorators. */
    // "emitDecoratorMetadata": true,         /* Enables experimental support for emitting type metadata for decorators. */
  },
  "include": [
    "src/**/*"
  ],
  "exclude": [
    "src/**/*.test.ts"
  ]
}

工程引用配置

  • references 指定工程引用依赖

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

    Project
      - src
        - client //客户端项目
          - index.ts // 客户端项目文件
          - tsconfig.json // 客户端配置文件
            {
              "extends": "../../tsconfig.json", // 继承基础配置
              "compilerOptions": {
                "outDir": "../../dist/client", // 指定输出目录
              },
              "references": [ // 指定依赖的工程
                {"path": "./common"}
              ]
            }
        - common // 前后端通用依赖工程
          - index.ts  // 前后端通用文件
          - tsconfig.json // 前后端通用代码配置文件
            {
              "extends": "../../tsconfig.json", // 继承基础配置
              "compilerOptions": {
                "outDir": "../../dist/client", // 指定输出目录
              }
            }
        - server // 服务端项目
          - index.ts // 服务端项目文件
          - tsconfig.json // 服务端项目配置文件
            {
              "extends": "../../tsconfig.json", // 继承基础配置
              "compilerOptions": {
                "outDir": "../../dist/server", // 指定输出目录
              },
              "references": [ // 指定依赖的工程
                {"path": "./common"}
              ]
            }
      - tsconfig.json // 前后端项目通用基础配置
        {
          "compilerOptions": {
            "target": "es5",
            "module": "commonjs",
            "strict": true,
            "composite": true, // 增量编译
            "declaration": true
          }
        } 

    这样配置以后,就可以单独的构建前后端项目。

    • 前端项目构建
    tsc -v src/client 
    • 后端项目构建
    tsc -b src/server 
    • 输出目录
    Project
     - dist 
      - client
        - index.js
        - index.d.ts
      - common
        - index.js
        - index.d.ts
      - server
        - index.js
        - index.d.ts

如果您觉得这篇文章有帮助,请点个赞吧~

分享文章

相关文章

更多文章 →
typescript2025-09-26
彻底讲透as const + keyof typeof
一、为什么要 “as const” 1、默认情况下,TS把字面量推断成”宽类型“ 于是你写 ‘foo’ | ‘bar’ 时, 一旦拼错成 ’fooo‘, TS不会拦你。 2、加上 as const ,TS会把它当成”不可变的精确字面量” 数组、对象同理: 二、keyof typeof: 把值世界映射到类型世界 typeof:能把运行时的值变成类型; keyof:能把对象类型变成联合类型 合起来就是:给我一个对象,我立刻推出它所有建的字面...
学习面试
typescript2025-02-26
TypeScript 中的 interface和 type 类型有什么区别?它们各自有什么用途?
在 TypeScript 中, 和 都可以用于定义类型,但它们有一些细微的差异和特定的应用场景。下面我们详细比较它们的 区别 、 相同点 以及 各自的用途 。 一、相同点 1. 描述对象的结构 : 和 都可以用来描述对象的结构。 2. 都支持可选属性和只读属性 : 3. 都可以扩展 (类似于继承)。不过扩展的方式不同(具体见下文)。 二、区别 | 特性 | interface | type | | | | | | 定义方式 | 使用 关...
学习面试面试官
typescript2024-08-07
TypeScript 中 `type` 和 `interface` 的区别
基本概念: 和 究竟是啥? 就是类型别名,用来给各种类型起个名字。可以是基本类型、对象类型、联合类型、交叉类型、元组等。 则专注于定义对象的结构和行为。它更像是面向对象编程中的蓝图,描述了对象应该拥有哪些属性和方法。 用途和功能:什么时候用 ,什么时候用 ? 的用途和功能 复杂类型组合 : 非常适合定义联合类型、交叉类型和元组。 灵活性高 :可以进行类型变换,比如条件类型和映射类型。 的用途和功能 描述对象结构 : 用来定义对象的形状,...
学习
typescript2024-05-13
破案了,为啥TypeScript5.3编译let、const一直是var
啊!2024才学TypeScript还有价值吗?!学的话,就用最新的上。 1.环境 8.15.4 Version 5.3.3 v20.10.0 2.背景&测试 使用pnpm安装了最新的TypeScript5.3.3,开始学习ts类型。 发现不论是let、const使用tsc编译完都是var。强迫症表示ES2016起不能接受var,尝试各种配置tsconfig.json后无效。 为什么let 经过tsc编译后 let= var 简化此图投...
学习
typescript2024-04-28
TS系列篇|类(class)
"不畏惧,不将就,未来的日子好好努力"——大家好!我是小芝麻😄 类(Class)定义了一件事物的抽象特点,包含它的属性和方法 1、定义类 在 中,我们也是通过 关键字来定义一个类, 使用 定义构造函数。 构造函数: constructor 主要用于初始化类的成员变量属性 类的对象创建时自动调用执行 没有返回值 2、类的继承 使用 关键字实现继承,子类中使用 关键字来调用父类的构造函数和方法。 子类继承父类后子类的实例就拥有了父类中的属...
学习
typescript2022-09-19
tsconfig.json配置详解

评论

请登录后发表评论

去登录
加载评论中...

目录