自动编译文件

编译文件时,使用-w指令后,TS编译器会自动监视文件的变化,并在文件发生变化时对文件进行重新编译
示例:
**tsc xxx.ts -w**
w表示watch

自动编译整个项目

如果直接使用tsc指令,则可以自动将当前项目下的所有ts文件编译为js文件
但是能直接使用tsc命令的前提时,要先在项目根目录下创建一个ts的配置文件tsconfig.json

tsconfig.json

这是是一个JSON文件,添加配置文件后,只需tsc命令即可完成对整个项目的编译
这个文件是ts编译器的配置文件,ts编译器可以根据它的信息来对代码进行编译

配置选项:

include

定义希望被编译文件所在的目录
用来指定哪些ts文件需要被编译

默认值

["**/*"]

示例:

  1. {
  2. "include":[
  3. "./src/**/*"
  4. ]
  5. }

上述示例中,根目录下的所有src目录下的任意目录的任意文件都会被编译


写路径时候*代表

  • 一个*表示的是任意文件
  • 两个**表示任意目录

exclude

定义需要排除在外的目录
不需要被编译的文件目录

默认值

  1. [
  2. "node_modules",
  3. "bower_components",
  4. "jspm_packages"
  5. ]

示例:

  1. {
  2. "include":[
  3. "./**/*"
  4. ],
  5. "exclude":[
  6. "node_modules",
  7. "bower_components",
  8. "jspm_packages",
  9. "./excludefile/**/*"
  10. ]
  11. }

extends

定义被继承的配置文件

示例

  1. {
  2. "extends": "./configs/base"
  3. }

上述示例中,当前配置文件中会自动包含config目录下base.json中的所有配置信息

files

指定被编译文件的列表,只有需要编译的文件少时才会用到

示例

{
    "files": [
        "a.ts",
        "b.ts",
        "c.ts",
        "d.ts",
        "e.ts",
        "f.ts",
    ]
}

列表中的文件都会被TS编译器所编译

compilerOptions

编译选项是配置文件中非常重要也比较复杂的配置选项
compilerOptions中包含多个子选项,用来完成对编译的配置

tsc -init

{
  "compilerOptions": {

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

    /* Basic Options */
    // "incremental": true,                         /* Enable incremental compilation */
    "target": "es5",                                /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', 'ES2021', or 'ESNEXT'. */
    "module": "commonjs",                           /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', 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', 'react', 'react-jsx' or 'react-jsxdev'. */
    // "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": "./",                              /* 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 */
    // "tsBuildInfoFile": "./",                     /* Specify file to store incremental compilation information */
    // "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. */
    // "strictBindCallApply": true,                 /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
    // "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. */
    // "noUncheckedIndexedAccess": true,            /* Include 'undefined' in index signature results */
    // "noImplicitOverride": true,                  /* Ensure overriding members in derived classes are marked with an 'override' modifier. */
    // "noPropertyAccessFromIndexSignature": true,  /* Require undeclared properties from index signatures to use element accesses. */

    /* 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": {},                                 /* 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": [],                             /* 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. */
    // "allowUmdGlobalAccess": true,                /* Allow accessing UMD globals from modules. */

    /* 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. */

    /* Advanced Options */
    "skipLibCheck": true,                           /* Skip type checking of declaration files. */
    "forceConsistentCasingInFileNames": true        /* Disallow inconsistently-cased references to the same file. */
  }
}

项目选项

target

设置ts代码编译的目标版本
用来指定ts被编译为的ES的版本

可选值

ES3(默认)、ES5、ES6/ES2015、ES7/ES2016、ES2017、ES2018、ES2019、ES2020、ESNext

示例

{
    "compilerOptions": {
        "target":"ES6"
    }
}

如上设置,我们所编写的ts代码将会被编译为ES6版本的js代码

lib

指定代码运行时所包含的库(宿主环境)
用来指定项目中要使用的库

{
    lib:[]
}

比如在使用document.getElementById("elementid");
使用的DOM的代码,DOM就是一个库

当lib为空时,DOM语句都不能使用

当代码不是在浏览器运行,而是在nodejs中运行的时候需要改lib
正常在浏览器中运行的话,lib是不需要设置的

可选值

示例

module

指定要使用的模块化的规范
一般推荐es2015这个版本

{
    "compilerOptions": {
        "target": "es2015",
        "module": "es2015"
    }
}

outDir

指定编译后文件所在目录

{
    "compilerOptions":{
      "outDir": "./dist"
  }
}

outFile

将代码合并为一个文件
设置outFile后,所有的全局作用域中的代码会合并到同一个文件中

这时module就得使用system或者amd

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

表示要把编译后的文件合并到app.js文件当中

allowJs

是否对JS文件进行编译
默认是false

{
    "compilerOptions":{
      "allowJs": true
  }
}

checkJs

是否检查js代码是否符合语法规范
默认是false

{
    "compilerOptions":{
      "checkJs": true
  }
}

removeComments

是否移除注释

{
    "compilerOptions":{
      "removeComments": true
  }
}

noEmit

不生成编译后的文件

{
    "compilerOptions":{
      "noEmit": true
  }
}

noEmitOnError

当有错误时不生成编译后的文件

{
    "compilerOptions":{
      "noEmitOnError": true
  }
}

alwaysStrict

用来设置编译后的文件是否使用严格模式
默认是false

{
    "compilerOptions":{
      "alwaysStrict": true
  }
}

noImplicitAny

不允许隐式的any类型
image.png

{
    "compilerOptions":{
      "noImplicitAny": true
  }
}

noImplicitThis

不允许隐式的不明确类型的this

{
    "compilerOptions":{
      "noImplicitThis": true
  }
}

image.png

strictNullChecks

严格的检查空值

{
    "compilerOptions":{
      "strictNullChecks": true
  }
}

image.png

strict

所有严格检查的总开关

{
    "compilerOptions":{
      "strict": true
  }
}

这个开了,其它几个检查的选项就都开了
image.png