侧边栏壁纸
  • 累计撰写 12 篇文章
  • 累计创建 6 个标签
  • 累计收到 1 条评论

目 录CONTENT

文章目录

tsconfig.json 配置文件 | TypeScript

Administrator
2023-11-20 / 0 评论 / 1 点赞 / 85 阅读 / 23973 字

tsconfig.json 配置文件

1. 什么是 tsconfig.json

编译文件

我们知道 tsc 命令可以将一个 ts 文件编译为 js 文件

tsc a.ts;

编译整个项目

那么当我们开发一个项目的时候都是使用的 ts 开发的,难道需要手动用 tsc 去编译每个文件么?不需要的。

只要在项目中初始化 tsconfig.json 文件,定义 tsc 的编译配置,此时执行 tsc 命令,会根据 tsconfig.json 配置文件自动编译整个项目。

tsconfig.json 文件生成

tsc --init

执行以上命令生成 tsconfig.json 默认初始化文件:

{
  "compilerOptions": {
    /* Visit https://aka.ms/tsconfig.json to read more about this file */
​
    /* Projects */
    /* 项目 */
    // "incremental": true,                              /* 保存 .tsbuildinfo 文件,增量编译 提高编译速度 */
    // "composite": true,                                /* 启用项目编译. */
    // "tsBuildInfoFile": "./",                          /* 指定增量编译文件 .tsbuildinfo 存储路径. */
    // "disableSourceOfProjectReferenceRedirect": true,  /* 复合文件中使用声明文件而不是源文件 */
    // "disableSolutionSearching": true,                 /* 复合项目中,跳转到引用的定义位置. */
    // "disableReferencedProjectLoad": true,             /* 使用该标志来禁用引用项目的自动加载,在复合项目比较大的时候比较有用. */
​
    /* Language and Environment */
    /* 语言环境 */
    "target": "es2016"                                   /* 指的是最终 `JavaScript` 会被编译的版本 */,    
    // "lib": ["dom", "es2015", "es2015.promise"],         /* 指定TS需要包含的内置类型包,一般包含这三个就够了 ["dom", "es2015", "es2015.promise"] */
    // "jsx": "preserve",                                /* 指定 JSX 代码生成:'preserve'、'react-native' 或 'react'。. */
    // "experimentalDecorators": true,                   /* 实验性阶段. */
    // "emitDecoratorMetadata": true,                    /* [高级配置] 为源文件中的装饰器声明提交元数据设计类型. */
    // "jsxFactory": "",                                 /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h' */
    // "jsxFragmentFactory": "",                         /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
    // "jsxImportSource": "",                            /* Specify module specifier used to import the JSX factory functions when using `jsx: react-jsx*`.` */
    // "reactNamespace": "",                             /* Specify the object invoked for `createElement`. This only applies when targeting `react` JSX emit. */
    // "noLib": true,                                    /* 禁用包括任何库文件,包括默认的lib.d.ts. */
    // "useDefineForClassFields": true,                  /* Emit ECMAScript-standard-compliant class fields. */
​
    /* Modules */
    /* 模块配置 */
    "module": "commonjs"                                 /* 指定所生成的模块代码风格. */,
    // "rootDir": "./",                                  /* 指定入口文件的根目录. */
    // "moduleResolution": "node",                       /* 模块解析策略,ts默认用node的解析策略,即相对的方式导入. */
    // "baseUrl": "./",                                  /* 解析非绝对模块名称的基目录, 配合paths一起用 */
    // 注意 配置 .d.ts 文件时, 在构建工具中可不进行配置,因为类型代码本身编译后也不在js文件中
    // "paths": {},                                      /* 重新映射包的相对路径, 相对于“baseUrl”的查找位置的条目 */
    //                                                   /* 配置别名路径, 让ts在编译时能够识别从而不报错, 但是执行的时候是找不到路径的,所以需要搭配构建工具的别名配置才可以 */  */   
    // "rootDirs": [],                                   /* Allow multiple folders to be treated as one when resolving modules. */
    // "typeRoots": [],                                  /* 用来指定默认的类型声明文件查找路径,默认为node_modules/@types; 指定typeRoots后ts会从指定的路径下搜索 `./node_modules/@types`. */
    // "types": [],                                      /* ts编译器会默认引入typeRoot下所有的声明文件, 有时希望只是编译某一部分,则可通过该属性配置. */
    // "allowUmdGlobalAccess": true,                     /* 允许全局引入UMD模块. */
    // "resolveJsonModule": true,                        /* 是否允许把json文件当做模块进行解析 */
    // "noResolve": true,                                /* Disallow `import`s, `require`s or `<reference>`s from expanding the number of files TypeScript should add to a project. */
​
    /* JavaScript Support */
    /* JS 支持配置 */
    // "allowJs": true,                                  /* 允许编译器编译JS,JSX文件 */
    // "checkJs": true,                                  /* 在经过类型检查的javascript文件中启用错误报告. */
    // "maxNodeModuleJsDepth": 1,                        /* Specify the maximum folder depth used for checking JavaScript files from `node_modules`. Only applicable with `allowJs`. */
​
    /* Emit */
    // 生成配置
    // "declaration": true,                              /* 项目中的js或ts文件生成对应的js文件和 .d.ts 文件. */
    // "declarationMap": true,                           /* 为每个对应的“.d.ts”文件生成一个源映射. */
    // "emitDeclarationOnly": true,                      /* 仅输出d.ts files并不生成js文件. */
    // "sourceMap": true,                                /* 创建生成js文件对应的map文件, 便于代码调试. */
    // "outFile": "./",                                  /* 连接输出到单个文件,但该属性对 module 有限制条件. */
    //                                                   /* 所有内容的输出文件.declaration为true时所有声明文件也都输出到一个 .d.ts 文件 *
    // "outDir": "./",                                   /* ts编译成js后的文件存放位置, 默认就在当前ts文件下生成js文件;  可配合rootDir入口指定使用 */
    // "removeComments": true,                           /* 移除注解. */
    // "noEmit": true,                                   /* 禁止Typescript编译器输出文件,使用三方规则. */
    // "importHelpers": true,                            /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
    // "importsNotUsedAsValues": "remove",               /* Specify emit/checking behavior for imports that are only used for types */
    // "downlevelIteration": true,                       /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
    // "sourceRoot": "",                                 /* Specify the root path for debuggers to find the reference source code. */
    // "mapRoot": "",                                    /* Specify the location where debugger should locate map files instead of generated locations. */
    // "inlineSourceMap": true,                          /* Include sourcemap files inside the emitted JavaScript. */
    // "inlineSources": true,                            /* Include source code in the sourcemaps inside the emitted JavaScript. */
    // "emitBOM": true,                                  /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
    // "newLine": "crlf",                                /* Set the newline character for emitting files. */
    // "stripInternal": true,                            /* Disable emitting declarations that have `@internal` in their JSDoc comments. */
    // "noEmitHelpers": true,                            /* Disable generating custom helper functions like `__extends` in compiled output. */
    // "noEmitOnError": true,                            /* 报错后不编译,启后 TS 将不会继续进行编译. */
    // "preserveConstEnums": true,                       /* Disable erasing `const enum` declarations in generated code. */
    // "declarationDir": "./",                           /* Specify the output directory for generated declaration files. */
    // "preserveValueImports": true,                     /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */
​
    /* Interop Constraints */
    /* 操作约束 */
    // "isolatedModules": true,                          /* Ensure that each file can be safely transpiled without relying on other imports. */
    // "allowSyntheticDefaultImports": true,             /* 允许export=导出,由import from 导入;. */
    "esModuleInterop": true                              /*允许export=导出,由import from 导入; 配置了 esModuleInterop: true 后, allowSyntheticDefaultImports属性也默认开启*/,
    // "preserveSymlinks": true,                         /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
    "forceConsistentCasingInFileNames": true             /* 强制大小写来区分文件名. */,
​
    /* Type Checking */
    /* 类型检查配置 (只要开启strict就行) */
    "strict": true,                                       /* Enable all strict type-checking options. */
    // "noImplicitAny": true,                            /* Enable error reporting for expressions and declarations with an implied `any` type.. */
    // "strictNullChecks": true,                         /* When type checking, take into account `null` and `undefined`. */
    // "strictFunctionTypes": true,                      /* 型参个数,和实参不同导致报错, 该选项可以让可编译通过*/
    // "strictBindCallApply": true,                      /* Check that the arguments for `bind`, `call`, and `apply` methods match the original function. */
    // "strictPropertyInitialization": true,             /* Check for class properties that are declared but not set in the constructor. */
    // "noImplicitThis": true,                           /* Enable error reporting when `this` is given the type `any`. */
    // "useUnknownInCatchVariables": true,               /* Type catch clause variables as 'unknown' instead of 'any'. */
    // "alwaysStrict": true,                             /* Ensure 'use strict' is always emitted. */
    // "noUnusedLocals": true,                           /* Enable error reporting when a local variables aren't read. */
    // "noUnusedParameters": true,                       /* Raise an error when a function parameter isn't read */
    // "exactOptionalPropertyTypes": true,               /* Interpret optional property types as written, rather than adding 'undefined'. */
    // "noImplicitReturns": true,                        /* Enable error reporting for codepaths that do not explicitly return in a function. */
    // "noFallthroughCasesInSwitch": true,               /* Enable error reporting for fallthrough cases in switch statements. */
    // "noUncheckedIndexedAccess": true,                 /* Include 'undefined' in index signature results */
    // "noImplicitOverride": true,                       /* Ensure overriding members in derived classes are marked with an override modifier. */
    // "noPropertyAccessFromIndexSignature": true,       /* Enforces using indexed accessors for keys declared using an indexed type */
    // "allowUnusedLabels": true,                        /* Disable error reporting for unused labels. */
    // "allowUnreachableCode": true,                     /* Disable error reporting for unreachable code. */
​
    /* Completeness */
    // "skipDefaultLibCheck": true,                      /* 可用 skipLibCheck替代. */
    "skipLibCheck": true                                 /* 忽略所有的声明文件( *.d.ts)的类型检查. */
  }
}
​

2. 顶层配置

  • files

    • 程序包含的文件,若列表文件没找到会报错

  • extends

    • 引入其它 tsconfig.json 文件

  • include / exclude

    • 包含指定模式的系列文件 / 排除系列文件,如 node_modules

  • references

    • 构造更小项目碎片,改善打包/编辑的迭代时间

  • compilerOptions

    • 项目配置

    • 语言环境

    • 模块配置

    • JS 支持配置

    • TS生成配置

    • 类型检查配置

    • Completeness

3. compilerOptions 属性

常用的 ts 编译配置内容

{
  "compilerOptions": {
    /* 语言环境 */
    "target": "ESNext",
    "lib": ["dom", "es2015", "es2015.promise"],
    "jsx": "preserve",
    /* 模块配置 */
    "module": "ESNext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "baseUrl": "./",
    "paths": {},
    /* JS 支持配置 */
    "allowJs": true,
    "checkJs": true,
    "removeComments": true,
    /* 生成配置 */
    "sourceMap": true,
    /* 操作约束 */
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    /* 类型检查配置 (只要开启strict就行) */
    "strict": true,
    /* Completeness */
    "skipLibCheck": true
  },
  "exclude": ["node_modules", "dist", "**/*.js", "**/*.md", "src/**/*.md"]
}
    

target

指的是最终 JavaScript 会被编译的版本;

选择项有:"ES5", "ES6", "ES2015", "ES2016", "ES2017", "ES2018", "ES2019", "ES2020", "ES2021", "ES2022", "ES2023", "ESNext" 推荐 ESNext

module

指定所生成的模块代码风格;

选项有:"CommonJS", "AMD", "System", "UMD", "ESNext" 推荐 CommonJS

strict

是否开启严格类型检查,如果开启该属性以下属性默认自动开启

启用 --strict 相当于 启用 --noImplicitAny, --noImplicitThis, --alwaysStrict, --strictNullChecks和 --strictFunctionTypes和--strictPropertyInitialization。

moduleResolution

模块解析策略,ts默认用node的解析策略,即相对的方式导入

esModuleInterop

允许导出/导入 语法; import from | export

removeComments

移除注解代码注释 (该配置保持默认就行; 前端打包工具也会帮助我们移除代码注释)

typeRoots

用来指定默认的类型声明文件查找路径,默认为node_modules/@types; 指定typeRoots后ts会从指定的路径下搜索

types

ts编译器会默认引入typeRoot下所有的声明文件, 有时希望只是编译某一部分,则可通过该属性配置

  • 小结

    1. typeRoots 是 tsconfig 中 compilerOptions 的一个配置项,typeRoots 下面的包会被 ts 编译器自动包含进来,typeRoots 默认指向 node_modules/@types。

    2. types 和 typeRoots 一样也是 compilerOptions 的配置,指定 types 后,typeRoots 下只有被指定的包才会被引入。

    3. @types 是 npm 的 scope 命名空间,和@babel 类似,@types 下的所有包会默认被引入,你可以通过修改 compilerOptions 来修改默认策略。

    4. typeRoot 和 types 属性应该配合一起使用

4. 常见配置案例

  • 这里只是一个通用的推荐配置,针对不同的框架

{
  "compilerOptions": {
    "target": "ES2015",
    "lib": ["dom", "dom.iterable", "esnext"], // 指定包含的内置类型,一般包含这三个就够了
    "module": "ESNext", // 推荐 ESM 规范,而不是 commonjs 规范
    "strict": true, // 强烈推荐开启,能防止很多错误,替代一部分的 eslint 功能
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true, // 强制大小写来区分文件名
    "resolveJsonModule": true, // 导入 json 文件必备配置
    "noFallthroughCasesInSwitch": true, // 确保 switch 语句中有 break、return、throw,否则会报错
  }
}

  • vue3-ts 模板配置

{
  "extends": "@vue/tsconfig/tsconfig.dom.json",
  "compilerOptions": {
    // 配置则是指定 TS 编译成 JS 的语言版本, 默认编译成 ES3
    "target": "esnext",
    // 指定项目的模块化规范
    "module": "esnext",
    // 模块解析策略,ts默认用node的解析策略,即相对的方式导入
    "moduleResolution": "bundler",
    // 严格模式
    "strict": true,
    "noLib": false,
    // 强制大小写来区分文件名
    "forceConsistentCasingInFileNames": true,
    // 配置了 esModuleInterop: true 后, allowSyntheticDefaultImports属性也默认开启
    "allowSyntheticDefaultImports": true,
    "strictFunctionTypes": false,
    "jsx": "preserve",
    "baseUrl": ".",
    // fix i18-ally 没有找到文案文件。
    "preserveValueImports": false,
    // 允许项目中存在js文件
    "allowJs": true,
    "sourceMap": true,
    // 允许export=导出,由import from 导入
    "esModuleInterop": true,
    // 是否允许把json文件当做模块进行解析
    "resolveJsonModule": true,
    "experimentalDecorators": true,
    // TS需要引用的库,即声明文件
    // 指定包含的内置类型,一般包含这三个就够了 ["dom", "dom.iterable", "esnext"]
    "lib": ["dom", "esnext"],
    "noImplicitAny": false,
    // 忽略所有的声明文件( *.d.ts)的类型检查。 (这里的配置和下边 include冲突 !! )
    "skipLibCheck": true,
    "removeComments": true,
    "types": ["node", "vite/client", "unplugin-vue-define-options/macros-global"],
    // 配置别名路径, 让ts在编译时能够识别从而不报错, 但是执行的时候是找不到路径的,所以需要搭配构建工具的别名配置才可以
    // 注意 配置 .d.ts 文件时, 在构建工具中可不进行配置,因为类型代码本身编译后也不在js文件中
    "paths": {
      "@/*": ["src/*"]
    }
  },
  "include": [
    "**/*.d.ts",
    "mock/**/*",
    "src/**/*.ts",
    "src/**/*.tsx",
    "src/**/*.vue",
    "types/**/*.d.ts",
    "types/**/*.ts",
    "vite.config.ts"
  ],
  "exclude": ["node_modules", "dist", "**/*.js", "**/*.md", "src/**/*.md"]
}

感谢

[三知之灵]

1

评论区