TyyeScript configuration file tsconfig.json detailed configuration, and general configuration

The tsconfig.json file is the configuration file of the TypeScript compiler, and the TypeScript compiler can compile the code according to its rules.

First, let's briefly explain the general configuration:

{
    /* 
        tsconfg.json是ts编译器的配置文件,ts编译器可以根据它的信息来对代码进行编译
        "include"  用来指定哪些ts文件需要被编译   一个*表示任意文件  两个*表示任意目录
        "exclude" 不需要被编译的文件目录  默认值 ["node_modules","bower_components","jspm_packages"]
    */
    "include": [
        "./src/**/*"
    ],
    // "exclude": [
    //     "./src/hello/**/*"
    // ],
    /* 
        compilerOptions 编译器的选项
    */
    "compilerOptions": {
        // target 用来指定被编译为的ES的版本
        "target": "ES2015",
        // module 指定要使用的模块化的规范 , 生成代码的模板标准
        //  'none' 'commonjs', 'amd', 'system', 'umd', 'es6', 'es2015', 'es2020', 'esnext'.
        "module":"ES2015",
        // lib用来指定项目中要使用的库
        // "lib": []
        // outDir 用来制动编译后文件所在的目录 , 指定输出目录
        "outDir": "./dist",
        // 将代码合并为一个文件  设置outFile后,所有的全局作用域中的代码回合并到同一个文件中
        // "outFile": "./dist/app.js"
 
        // 是否对js文件镜像编译,默认false, 允许编译器编译JS,JSX文件
        "allowJs": true,
        // 是否检查js代码是否符合语法规范,默认false,允许在JS文件中报错,通常与allowJS一起使用
        "checkJs": true,
        // 是否去掉注释 默认false
        "removeComments": true,
        //不生成编译后的文件 默认false ,不输出文件,即编译后不会生成任何js文件
        "noEmit": false,
        // 当有错误时不生成编译后文件,发送错误时不输出任何文件
        "noEmitOnError": false,
        // 所有严格模式的总开关,开启所有严格的类型检查
        "strict": false,
        // 用来设置编译后的文件是否使用严格模式,默认false,在代码中注入'use strict'
        "alwaysStrict": false,
        //不允许隐式的any类型
        "noImplicitAny": false,
        // 不允许不明确的this,不允许this有隐式的any类型
        "noImplicitThis": false,
        // 严格的检查空值,不允许把null、undefined赋值给其他类型的变量
        "strictNullChecks": true,
       "incremental": true, // TS编译器在第一次编译之后会生成一个存储编译信息的文件,第二次编译会在第一次的基础上进行增量编译,可以提高编译的速度        "tsBuildInfoFile": "./buildFile", // 增量编译文件的存储位置        "diagnostics": true, // 打印诊断信息        "outFile": "./app.js", // 将多个相互依赖的文件生成一个文件,可以用在AMD模块中,即开启时应设置"module": "AMD",        "lib": ["DOM", "ES2015", "ScriptHost", "ES2019.Array"], // TS需要引用的库,即声明文件,es5 默认引用dom、es5、scripthost,如需要使用es的高级版本特性,通常都需要配置,如es8的数组新特性需要引入"ES2019.Array",        "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": [], // 加载的声明文件包      "noEmitHelpers": true, // 不生成helper函数,减小体积,需要额外安装,常配合importHelpers一起使用        "importHelpers": true, // 通过tslib引入helper函数,文件必须是模块        "downlevelIteration": true, // 降级遍历器实现,如果目标源是es3/5,那么遍历器会有降级的实现        "jsx": "preserve", // 指定 jsx 格式        "strictFunctionTypes": true, // 不允许函数参数双向协变        "strictPropertyInitialization": true, // 类的实例属性必须初始化        "strictBindCallApply": true, // 严格的bind/call/apply检查        "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// 打印编译的文件(包括引用的声明文件)

    }
}

Detailed configuration option description
  include: Specify the directory where the compiled file is located.
  exclude: Specify directories that do not need to be compiled.
  extends: Specifies the configuration file to be inherited.
  files: Specifies the files to be compiled.
  references: project references, a new feature in TS 3.0, which allows organizing TS programs into smaller parts.
  Tips: When filling in the path, ** means any directory, and * means any file.

compilerOptions
​ defines the project's runtime expectations, how and where JavaScript is emitted, and the level of integration with existing JavaScript code.

project options

  incremental: Whether to enable incremental compilation, which means that only the added content will be compiled when compiling again, default: false.
  target: Specify the version where ts is compiled into ES.
  module: Specifies the modular specification used by the compiled code.
  lib: Specifies the library used when the project is running.
  outDir: Specifies the directory where the compiled file is located.
  outFile: Compile and merge the code into one file. By default, all codes in the global scope are merged into one file.
  rootDir: Specifies the root directory of the input file. By default, the current project directory is the root directory.
  allowJs: whether to compile js files, default: false.
  checkJs: Whether to check whether the js code conforms to the grammar specification. When using checkJs, you must use allowJs, default: false.
  removeComments: whether to remove comments, default: false
  noEmit: do not generate compiled files, default: false.
  jsx: Specifies the development environment used for JSX code generation.
  plugins: A list of language service plugins to run in the editor.
  declaration: whether to generate the corresponding .d.ts declaration file, default: false.
  declarationMap: Whether to generate a Map file for each corresponding .d.ts file. When using this function, it needs to be used together with declaration or composite. Default: false.
  sourceMap: whether to generate the corresponding Map mapping file, default: false.
  composite: whether to enable project compilation, enable this function, will generate the directory where the compiled file is located, and enable declaration, declarationMap and incremental at the same time, default: false.
  tsBuildInfoFile: Specifies the location of the incremental compilation information file. When using this function, the incremental option must be enabled.
  importHelpers: Whether to import helper functions from the tslib module, default: false.
  downlevelIteration: whether to provide full support for iterable objects for conversion to older versions of JS, default: false.
  isolatedModules: Whether to convert each file into a separate module, default: false.
Strict check
  strict: Whether to enable all strict checks, default: false, all strict check options will be enabled after startup.
  alwaysStrict: Whether to parse in strict mode and emit "use strict" for each source file, default: false.
  noImplicitAny: whether to prohibit the implicit any type, default: false.
  noImplicitThis: Whether to prohibit this of an ambiguous type, default: false.
  strictNullChecks: whether to enable strict null checks, default: false.
  strictBindCallApply: Whether to enable strict 'bind', 'call' and 'apply' methods on functions, default: false.
  strictFunctionTypes: Whether to enable strict checking of function types, default: false.
  strictPropertyInitialization: Whether to enable strict inspection of property initialization of the class, default: false.
Module resolution option
  moduleResolution: specifies the module resolution strategy, node or classic
  baseUrl: the base directory used to resolve non-absolute module names, and relative modules are not affected.
  paths: used to set the path mapping relationship of the module name based on baseUrl.
  rootDirs: Put multiple directories in one virtual directory, and the imported location of the file changes after running the compilation, and no error will be reported.
  typeRoots: Specify the path list of the declaration file or folder
  type: Used to specify the modules that need to be included and include them in the global scope.
  allowSyntheticDefaultImports: Whether to allow default imports from modules without default exports, default: false.
  esModuleInterop: Whether to allow interoperability between CommonJS and ES modules by creating namespace objects for all imported modules. When the option is turned on, the allowSyntheticDefaultImports option is also automatically turned on. Default: false.
  preserveSymlinks: Whether to not resolve the real path of symbolic links, this is to reflect the same flag in Node.js, default: false.
  allowUmdGlobalAccess: Allows you to access UMD exports as global variables from within the module file. If this option is not used, an import statement is required for exports from UMD modules. Default: false.
Map option
  sourceRoot: Specifies where the debugger should target TypeScript files instead of relative source locations.
  mapRoot: Specifies where the debugger locates the Map file, rather than the generated location.
  inlineSourceMap: Whether to nest the content of the Map file into the JS file, which will cause the JS file to become larger, but it will be convenient in some cases, default: false.
  inlineSources: Whether to include the original content of the .ts file in the .map file as an embedded string, default: false.
Additional check
  noUnusedLocals: whether to check for unused local variables, default: false.
  noUnusedParameters: whether to check for unused parameters, default: false.
  noImplicitReturns: Check whether the function does not contain an implicit return value, default: false.
  noImplicitOverride: Whether to check whether the subclass inherits from the base class, the overloaded function name is out of sync with the base class function, default: false.
  noFallthroughCasesInSwitch: Check whether there is a case in the switch without using break to jump out, default: false.
  noUncheckedIndexedAccess: Whether to use index signatures to describe objects with unknown keys but known values, default: false.
  noPropertyAccessFromIndexSignature: whether to access fields and "index" ( obj["key"]) via " . "(obj.key) syntax, and the consistency between the way properties are declared in types, default: false.
experimental options
  experimentalDecorators: Whether to enable experimental support for decorators. Decorators are a language feature that has not been fully approved by the JavaScript specification. Default: false.
  emitDecoratorMetadata: Enables experimental support for emitting type metadata for decorators, default: false.
Advanced option
  allowUnreachableCode: whether to allow unreachable code (undefined / true / false), default: undefined.
  undefined: Suggest to the editor as a warning.
  true: Unused tags are ignored.
  false: Raises a compiler error about unused labels.
  allowUnusedLabels: Whether to allow unused labels (undefined / true / false), default: undefined.
  undefined: Suggest to the editor as a warning.
  true: Unused tags are ignored.
  false: Raises a compiler error about unused labels.
  Whether assumeChangesOnlyAffectDirectDependencies avoids rechecking/rebuilding all files that might really be affected, but only rechecks/rebuilds files that have changed and files that import them directly, default: false.
  charset: character set (deprecated), default: utf8
  declarationDir: Provides a way to configure the root directory for issuing declaration files.
  diagnostics: used to output diagnostic information for debugging
  disableReferencedProjectLoad: Whether to disable all available projects from being loaded into memory, default: false.
  disableSizeLimit: In order to avoid possible memory expansion problems when dealing with very large JS projects, there is an upper limit to the amount of memory that TS will allocate, default: false.
  disableSolutionSearching: When searching for all references or jumping to definitions in the editor, disable the inclusion of compound items, default: false.
  disableSourceOfProjectReferenceRedirect: whether to disable project reference source redirection, default: false.
  emitBOM: Controls whether TypeScript emits a byte order mark (BOM) when writing output files, default: false.
  emitDeclarationOnly: Whether to only emit .d.ts files and not emit .js files. When using this option, it needs to be used together with declaration or composite. Default: false.
  explainFiles: explain files, this option is used to debug how files become part of compilation, default: false.
  extendedDiagnostics: Whether to check the time spent by TS at compile time, default: false.
  forceConsistentCasingInFileNames: Whether to distinguish the case rules of the file system, default: false.
  generateCpuProfile: Let TS issue a CPU profile during compilation, only call --generateCpuProfile tsc-output.cpuprofile through terminal or CLI.
  importsNotUsedAsValues: This flag controls how the import works, there are 3 different options: remove, preserve and error.
  jsxFactory: When using the classic JSX runtime to compile JSX elements, change the function called in the .js file, default: React.createElement.
  jsxFragmentFactory: Specifies the JSX fragment factory function to use when emitting against react JSX with the jsxFactory compiler option specified.
  jsxImportSource: When using jsx as react-jsx or react-jsxdev in TS 4.1, declares a module specifier for importing jsx and jsxs factory functions.
  keyofStringsOnly: When applying a type with a string index signature, this flag changes the key value of the type operator to return string instead of string|number, deprecated, default: false.
  listEmittedFiles: Whether to print the name of the file generated by the compilation part to the terminal, default: false.
  listFiles: Whether to print the name of the compiled file part, default: false.
  maxNodeModuleJsDepth: The maximum dependency depth to search and load JavaScript files under node_modules, default: 0.
  newLine: Specifies the newline rule to use when emitting the file, CRLF (dos) or LF (unix).
  noEmitHelpers: Whether to use the global scope helper function to provide implementation, and completely turn off the emission of the helper function instead of using importhelper to import the helper function, default: false.
  noEmitOnError: Do not compile when there is an error, default: false.
  noErrorTruncation: Whether to disable truncation of error messages, deprecated, default: false.
  noImplicitUseStrict: Whether to prohibit no implicit strict mode, default: false.
  noLib: Whether to prohibit automatic inclusion of any library files, default: false.
  noResolve: Whether to disable the addition of parsed files to the program; by default, TS will check the initial file set of import and reference directives, and add these parsed files to your program, default: false.
  noStrictGenericChecks: whether to disable strict generic checks, default: false.
  out: This option calculates the final file position in an unpredictable or consistent way, which is deprecated.
  preserveConstEnums: Whether to prohibit the deletion of declarations in the generated code of enumeration constants, default: false.
  reactNamespace: React namespace, use jsxFactory instead.
  resolveJsonModule: whether to parse the JSON module, default: false.
  skipDefaultLibCheck: Whether to skip the type check of the default library declaration file, default: false.
  skipLibCheck: Whether to skip the type checking of declaration files, which can save time at the expense of type system accuracy during compilation, default: false.
  stripInternal: Whether to prohibit the code with the @internal annotation in the JSDoc annotation to issue a statement, default: false.
  suppressExcessPropertyErrors: whether to disable reporting too many property errors, default: false.
  suppressImplicitAnyIndexErrors: Whether to suppress errors of implicit any indexes, default: false.
  traceResolution: When trying to debug why the module was not included. Enable this option to have TypeScript print information about the parsing process for each processed file, default: false.
  useDefineForClassFields: This flag is used as part of migration to the upcoming standard version of class fields, default: false.
Command line
  preserveWatchOutput: Whether to preserve stale console output in watch mode instead of clearing the screen every time something changes, default: false.
  pretty: Whether to use color to style contextual errors and messages, default: true.
  watchOptions
configures how TypeScript's --watch works.

monitoring options

  watchFile: Strategy to watch a single file, default: useFsEvents
  fixedPollingInterval: Check each file for changes multiple times per second at a fixed interval.
  priorityPollingInterval: Check each file for changes many times per second, but use a heuristic to check some types of files less frequently than others.
  dynamicPriorityPolling: Use a dynamic queue where files that are not modified frequently will be checked less frequently.
  useFsEvents: Attempts to use the operating system/filesystem's native events for file changes.
  useFsEventsOnParentDirectory: Attempts to use the operating system/filesystem's native events to listen for changes in the file's parent directory.
  watchDirectory: The strategy of how to monitor the entire directory tree in a system that lacks recursive file monitoring. Default: useFsEvents
  fixedPollingInterval: Check each directory for changes multiple times per second at a fixed interval.
  dynamicPriorityPolling: Use a dynamic queue where infrequently modified directories will be checked less frequently.
  useFsEvents: Attempts to use the operating system/filesystem's native events for directory changes.
  fallbackPolling: When using file system events, this option specifies the polling strategy to use when the system runs out of native file watchers and/or does not support native file watchers, default: dynamicPriorityPolling fixedPollingInterval: multiple times per second at fixed
  intervals Check each file for changes.
  priorityPollingInterval: Check each file for changes many times per second, but use a heuristic to check some types of files less frequently than others.
  dynamicPriorityPolling: Use a dynamic queue where files that are not modified frequently will be checked less frequently.
  synchronousWatchDirectory: Disables lazy watch on directories.
  synchronousWatchDirectory: Call the callback synchronously on platforms that do not natively support recursive watch, and update the state of the directory watcher, default: false.
  excludeDirectories: Use exclude directories to drastically reduce the number of files being watched during --watch.
  excludeFiles: Use excludeFiles to remove a specific set of files from being watched.


typeAcquisition
  is only important for JavaScript projects.

  1. Type acquisition

  enable: Provides configuration to disable type acquisition in JavaScript projects, default: false.
  include: Use include to specify which types should be used from absolute types.
  exclude: Provides configuration for disabling type acquisition of a module in a JavaScript project
  disableFilenameBasedTypeAcquisition: Whether to disable type acquisition based on file name, TypeScript type acquisition can infer which types should be added based on the file name in the project, default: false.

Guess you like

Origin blog.csdn.net/weixin_44786530/article/details/130157465