TS编译选项

# TS编译选项

今天我们主要来学习TS的编译选项

# 编译TS

# 自动编译文件

编译文件时,使用 -w 指令后,TS编译器会自动监视文件的变化,并在文件发生变化时对文件进行重新编译。

tsc xxx.ts -w

一个文件一个文件的编译太麻烦了,我们可以对整个项目进行编译

# 自动编译整个项目

首先在项目根目录下创建一个ts的配置文件 tsconfig.json,然后就可以使用tsc指令,编译项目下的所有ts文件为js文件,当然也可以开启监视模式tsc -w监视所有的文件

我们使用 tsc --init 可以初始化一个tsconfig.json文件,通过对配置文件的设置可以进行自定义的ts编译

{
  "compilerOptions": {
    /* Visit https://aka.ms/tsconfig.json to read more about this file */

    /* Projects */
    // "incremental": true,                              /* Enable incremental compilation */
    // "composite": true,                                /* Enable constraints that allow a TypeScript project to be used with project references. */
    // "tsBuildInfoFile": "./",                          /* Specify the folder for .tsbuildinfo incremental compilation files. */
    // "disableSourceOfProjectReferenceRedirect": true,  /* Disable preferring source files instead of declaration files when referencing composite projects */
    // "disableSolutionSearching": true,                 /* Opt a project out of multi-project reference checking when editing. */
    // "disableReferencedProjectLoad": true,             /* Reduce the number of projects loaded automatically by TypeScript. */

    /* Language and Environment */
    "target": "es5",                                     /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
    // "lib": [],                                        /* Specify a set of bundled library declaration files that describe the target runtime environment. */
    // "jsx": "preserve",                                /* Specify what JSX code is generated. */
    // "experimentalDecorators": true,                   /* Enable experimental support for TC39 stage 2 draft decorators. */
    // "emitDecoratorMetadata": true,                    /* Emit design-type metadata for decorated declarations in source files. */
    // "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,                                    /* Disable including any library files, including the default lib.d.ts. */
    // "useDefineForClassFields": true,                  /* Emit ECMAScript-standard-compliant class fields. */

    /* Modules */
    "module": "commonjs",                                /* Specify what module code is generated. */
    // "rootDir": "./",                                  /* Specify the root folder within your source files. */
    // "moduleResolution": "node",                       /* Specify how TypeScript looks up a file from a given module specifier. */
    // "baseUrl": "./",                                  /* Specify the base directory to resolve non-relative module names. */
    // "paths": {},                                      /* Specify a set of entries that re-map imports to additional lookup locations. */
    // "rootDirs": [],                                   /* Allow multiple folders to be treated as one when resolving modules. */
    // "typeRoots": [],                                  /* Specify multiple folders that act like `./node_modules/@types`. */
    // "types": [],                                      /* Specify type package names to be included without being referenced in a source file. */
    // "allowUmdGlobalAccess": true,                     /* Allow accessing UMD globals from modules. */
    // "resolveJsonModule": true,                        /* Enable importing .json files */
    // "noResolve": true,                                /* Disallow `import`s, `require`s or `<reference>`s from expanding the number of files TypeScript should add to a project. */

    /* JavaScript Support */
    // "allowJs": true,                                  /* Allow JavaScript files to be a part of your program. Use the `checkJS` option to get errors from these files. */
    // "checkJs": true,                                  /* Enable error reporting in type-checked JavaScript files. */
    // "maxNodeModuleJsDepth": 1,                        /* Specify the maximum folder depth used for checking JavaScript files from `node_modules`. Only applicable with `allowJs`. */

    /* Emit */
    // "declaration": true,                              /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
    // "declarationMap": true,                           /* Create sourcemaps for d.ts files. */
    // "emitDeclarationOnly": true,                      /* Only output d.ts files and not JavaScript files. */
    // "sourceMap": true,                                /* Create source map files for emitted JavaScript files. */
    // "outFile": "./",                                  /* Specify a file that bundles all outputs into one JavaScript file. If `declaration` is true, also designates a file that bundles all .d.ts output. */
    // "outDir": "./",                                   /* Specify an output folder for all emitted files. */
    // "removeComments": true,                           /* Disable emitting comments. */
    // "noEmit": true,                                   /* Disable emitting files from a compilation. */
    // "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,                            /* Disable emitting files if any type checking errors are reported. */
    // "preserveConstEnums": true,                       /* Disable erasing `const enum` declarations in generated code. */
    // "declarationDir": "./",                           /* Specify the output directory for generated declaration files. */

    /* Interop Constraints */
    // "isolatedModules": true,                          /* Ensure that each file can be safely transpiled without relying on other imports. */
    // "allowSyntheticDefaultImports": true,             /* Allow 'import x from y' when a module doesn't have a default export. */
    "esModuleInterop": true,                             /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type compatibility. */
    // "preserveSymlinks": true,                         /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
    "forceConsistentCasingInFileNames": true,            /* Ensure that casing is correct in imports. */

    /* Type Checking */
    "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,                      /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
    // "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,                      /* Skip type checking .d.ts files that are included with TypeScript. */
    "skipLibCheck": true                                 /* Skip type checking all .d.ts files. */
  }
}

下面我们在介绍tsconfig.json文件中的一些配置选项

# 配置选项

总览

官方文档 TypeScript: TSConfig Reference - Docs on every TSConfig option (typescriptlang.org) (opens new window)

{
  "compilerOptions": {
    "target": "es5",   // 指定 ECMAScript 目标版本: 'ES5'
    "module": "commonjs",  // 指定使用模块: 'commonjs', 'amd', 'system', 'umd' or 'es2015'
    "moduleResolution": "node",     // 选择模块解析策略
    "experimentalDecorators": true,  // 启用实验性的ES装饰器
    "allowSyntheticDefaultImports": true,   // 允许从没有设置默认导出的模块中默认导入。
    "sourceMap": true,   // 把 ts 文件编译成 js 文件的时候,同时生成对应的 map 文件
    "strict": true,  // 启用所有严格类型检查选项
    "noImplicitAny": true,  // 在表达式和声明上有隐含的 any类型时报错
    "alwaysStrict": true,  // 以严格模式检查模块,并在每个文件里加入 'use strict'
    "declaration": true,   // 生成相应的.d.ts文件
    "removeComments": true,   // 删除编译后的所有的注释
    "noImplicitReturns": true,  // 不是函数的所有返回路径都有返回值时报错
    "importHelpers": true,  // 从 tslib 导入辅助工具函数
    "lib": ["es6", "dom"],  // 指定要包含在编译中的库文件
    "typeRoots": ["node_modules/@types"],
    "outDir": "./dist", // 编译结果输出目录
    "rootDir": "./src" // 源代码ts所在目录
  },
  "include": [  
    "./src/**/*.ts"
  ],
  "exclude": [
    "node_modules",
    "dist",
    "**/*.test.ts",
  ]
}

# ① include

重要

  • 是一个数组,用来指定需要编译的ts文件,其中 *表示任意文件 **表示任意目录

  • 默认值:["**/*"]

"include":["src/**/*", "test/**/*"] // 所有src目录和test目录下的文件都会被编译

# ② exclude

  • 定义不需要被编译的文件目录

  • 默认值:["node_modules", "bower_components", "jspm_packages"]

"exclude": ["./src/hello/**/*"]  // src下hello目录下的文件都不会被编译

# ③ extends

  • 定义被继承的配置文件
"extends": "./configs/base" // 当前配置文件中会自动包含config目录下base.json中的所有配置信息

# ④ files

  • 指定被编译文件的列表,只有需要编译的文件少时才会用到
"files": [
    "core.ts",
    "sys.ts",
    "types.ts",
    "scanner.ts",
    "parser.ts",
    "utilities.ts",
    "binder.ts",
    "checker.ts",
    "tsc.ts"
]
  • 列表中的文件都会被TS编译器所编译

# ⑤ compilerOptions

重要 编译选项,在compilerOptions中包含多个子选项,用来完成对编译的配置

对于这些选项有哪些可选值,我们可以随便写一个值,编辑器会提示我们有哪些可选值

image.png

# ① target

  • 设置ts代码编译的目标版本

  • 可选值: "ES3"(默认), "ES5", "ES6", "ES2015", "ES2016", "ES2017", "ES2018", "ES2019", "ES2020", "ES2021", "ESNext".

"compilerOptions": {
    "target": "ES6"
}
  • 如上设置,我们所编写的ts代码将会被编译为ES6版本的js代码

# ② lib

  • 指定代码运行时所包含的库(宿主环境)

  • 可选值:"ES5", "ES6", "ES2015", "ES2015.Collection", "ES2015.Iterable", "ES2015.Promise", "DOM", "DOM.Iterable", "ScriptHost", "WebWorker", "WebWorker.ImportScripts"......

"compilerOptions": {
    "lib": ["ES6", "DOM"]
}

一般来说,如果是运行在浏览器环境下的,就不需要自己单独设置这个

# ③ module

  • 设置编译后代码使用的模块化系统

  • 可选值:"CommonJS", "AMD", "System", "UMD", "ES6", "ES2015", "ES2020", "ESNext", "None", "es2022", "node12", "nodenext"

"compilerOptions": {
    "module": "CommonJS"
}

# ④ outDir

  • 编译后文件的所在目录

  • 默认情况下,编译后的js文件会和ts文件位于相同的目录,设置outDir后可以改变编译后文件的位置

"compilerOptions": {
    "outDir": "./dist"
}
  • 设置后编译后的js文件将会生成到dist目录。可以将源码与编译后的代码分开存放

# ⑤ outFile

  • 将所有的文件编译为一个js文件

  • 默认会将所有的编写在全局作用域中的代码合并为一个js文件,如果 module 制定了 None、System 或 AMD 则会将模块一起合并到文件之中

"compilerOptions": {
    "outFile": "./dist/app.js"
}

这种合并,我们应该交给打包工具去做,我们后面会说

# ⑥ rootDir

  • 指定代码的根目录,默认情况下编译后文件的目录结构会以最长的公共目录为根目录,通过rootDir可以手动指定根目录
"compilerOptions": {
    "rootDir": "./src"
}

# ⑦ 其他配置

标题 功能
allowJs 是否对js文件编译,默认值:false
checkJs 是否对js文件进行语法检查,默认值:false
removeComments 是否删除注释,默认值:false
noEmit 不生成编译后的文件,默认值:false
noEmitOnError 当有错误的时候不生成编译后的文件,默认值:false
sourceMap 是否生成sourceMap,默认值:false

# ⑧ 严格检查

标题 功能
strict 启用所有的严格检查,设置后相当于开启了所有的严格检查,默认值:false
alwaysStrict 总是以严格模式对代码进行编译,默认值:false
noImplicitAny 禁止隐式的any类型,默认值:false
noImplicitThis 禁止类型不明确的this,默认值:false
strictBindCallApply 严格检查bind、call和apply的参数列表,默认值:false
strictFunctionTypes 严格检查函数的类型,默认值:false
strictNullChecks 严格的空值检查,默认值:false
strictPropertyInitialization 严格检查属性是否初始化,默认值:false

# ⑨ 额外检查

标题 功能
noFallthroughCasesInSwitch 检查switch语句包含正确的break
noImplicitReturns 检查函数没有隐式的返回值
noUnusedLocals 检查未使用的局部变量
noUnusedParameters 检查未使用的参数
allowUnreachableCode 检查不可达代码;true:忽略不可达代码,false:不可达代码将引起错误
noEmitOnError 有错误的情况下不进行编译,默认值:false
上次更新: 2022/5/14 10:02:51