Typescript编译器选项:tsconfig.json文件实例

372 阅读5分钟

typecript 配置文件

每个typescript项目都有tsconfig.json文件根目录。tsconfig是typescript配置文件的缩写。这个文件包含typecript编译器的所有配置参数。Angular 2+是基于typecript的。每个Angular项目在项目根目录下都有这个文件。浏览器无法理解typescript文件,所以有一个叫做compile/transpile的过程来编译typescript代码并生成javascript代码。

在编译阶段,你在这个文件中指定的所有配置参数都会被考虑。一旦在全局或本地安装了typescript(已经发表了一篇关于如何安装typescript语言的文章),就可以使用tsc命令。

Typescript文件可以用tsc命令Angular cli工具生成

使用tsc命令行

这将在根目录下输出配置文件,其基本配置选项定义如下 以下是tsconfig.json文件样本

  
{  
  "compilerOptions": {  
    /* Basic Options */  
    "target": "es5",                          /* 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. */  
    // "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. */  
    // "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": {},                           /* 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. */  
  
    /* 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. */  
  }  
}  

Angular cli typecript编译器选项

Angular CLI是一个用于从头开始生成一个新的Angular应用程序的工具。你不需要写任何文件来建立一个项目。只需一个命令,你的应用程序原型源代码就可以了。这个工具也会在项目根目录下生成一个typescript配置文件。

我们将通过不同的编译器选项与详细的解释目标选项:-
Typescript编译成javascript。有不同版本的javascript - ES5, ES6, 和ES7。这个选项提供了与相应的javascript目标版本相适应的生成文件,可能的值是ES3 - 默认,ES5,ES6(ES2015),ES2016,ES2017,ESNEXT。

模块选项

这个选项是使用模块来生成代码。模块有不同的类型,如CommonJS、None、System、UMD、AMD、ES6。如果目标指定为ES3或ES5,默认选项为CommonJS,否则ES6为默认模块。

实验性装饰器选项

ES2017提出的实验性装饰器还没有被接受。如果我们在typecript源代码中使用这些装饰器,会出现错误。这个选项可以启用typescript的装饰器。装饰器从ES2017版本开始被支持。通过设置该选项,错误将被忽略。默认情况下,它是false。

emitDecoratorMetadata选项

这个选项是装饰器元数据所需要的。默认情况下,它是false。元数据是ES2017规范中的一项功能,用于告知类、方法或函数的运行时信息。元数据是类型脚本反射API,提供了关于装饰器的信息。

这个选项将在你的对象的元数据中保留类型信息。

保存时编译选项

这个选项与typescript无关,适用于visual studio、web storm和atom等IDE。如果Typescript文件有任何变化,它会自动保存并编译成javascript代码。

baseUrls/path选项

这个选项允许Typescript从这个位置提取类型文件。

alwaysStrict选项

这个选项允许启用类型安全检查。编译器以严格模式编译所有的typescript文件,如果有的话会发出警告。在每个文件中,它在每个生成的javascript文件中包括'use Strict'。

sourceMap选项
默认为false。如果为true,生成源码图用于调试。

AllowJS选项
该选项允许将javascript源代码作为转码过程的一部分进行编译。默认为false。

strictNullChecks选项
当strictNullChecks=false时,下面的代码可以工作,因为null和undefined类型可以被分配到数字类型。

let numberVariable: number = 45;  
numberVariable = null; // no issues  
numberVariable = undefined; // no issues  

当strictNullChecks=true时,下面的代码不工作。

let numberVariable = undefined;  
numberVariable = null; // As undefined and null are different  

outDir选项
该选项允许编译器在该目录下生成输出文件。

removeComments选项
默认为false。从生成的源文件中删除注释。

Include and Exclude options
这个Include选项将允许在编译源代码时添加这个文件。以同样的方式,我们可以指定将文件从代码编译中排除。

  
{  
    "include": [          "src/main/webapp/app",          "src/main/webapp/app/app.main.ts",          "src/test/javascript/"      ],  
    exclude": [          "node_modules",      ]  
}