TypeScript学习(tsconfig.json 配置文件)

使用tsconfig.json文件配置项目编译选项

{
    
    
  "compilerOptions": {
    
    

    /* 基本选项 */
    "target": "es5",                       // 指定 ECMAScript 目标版本: 'ES3' (default), 'ES5', 'ES6'/'ES2015', 'ES2016', 'ES2017', or 'ESNEXT'
    "module": "commonjs",                  // 指定使用模块: 'commonjs', 'amd', 'system', 'umd' or 'es2015'
    "lib": [],                             // 指定要包含在编译中的库文件
    "allowJs": true,                       // 允许编译 javascript 文件
    "checkJs": true,                       // 报告 javascript 文件中的错误
    "jsx": "preserve",                     // 指定 jsx 代码的生成: 'preserve', 'react-native', or 'react'
    "declaration": true,                   // 生成相应的 '.d.ts' 文件
    "sourceMap": true,                     // 生成相应的 '.map' 文件
    "outFile": "./",                       // 将输出文件合并为一个文件
    "outDir": "./",                        // 指定输出目录
    "rootDir": "./",                       // 用来控制输出目录结构 --outDir.
    "removeComments": true,                // 删除编译后的所有的注释
    "noEmit": true,                        // 不生成输出文件
    "importHelpers": true,                 // 从 tslib 导入辅助工具函数
    "isolatedModules": true,               // 将每个文件作为单独的模块 (与 'ts.transpileModule' 类似).

    /* 严格的类型检查选项 */
    "strict": true,                        // 启用所有严格类型检查选项
    "noImplicitAny": true,                 // 在表达式和声明上有隐含的 any类型时报错
    "strictNullChecks": true,              // 启用严格的 null 检查
    "noImplicitThis": true,                // 当 this 表达式值为 any 类型的时候,生成一个错误
    "alwaysStrict": true,                  // 以严格模式检查每个模块,并在每个文件里加入 'use strict'

    /* 额外的检查 */
    "noUnusedLocals": true,                // 有未使用的变量时,抛出错误
    "noUnusedParameters": true,            // 有未使用的参数时,抛出错误
    "noImplicitReturns": true,             // 并不是所有函数里的代码都有返回值时,抛出错误
    "noFallthroughCasesInSwitch": true,    // 报告 switch 语句的 fallthrough 错误。(即,不允许 switch 的 case 语句贯穿)

    /* 模块解析选项 */
    "moduleResolution": "node",            // 选择模块解析策略: 'node' (Node.js) or 'classic' (TypeScript pre-1.6)
    "baseUrl": "./",                       // 用于解析非相对模块名称的基目录
    "paths": {
    
    },                           // 模块名到基于 baseUrl 的路径映射的列表
    "rootDirs": [],                        // 根文件夹列表,其组合内容表示项目运行时的结构内容
    "typeRoots": [],                       // 包含类型声明的文件列表
    "types": [],                           // 需要包含的类型声明文件名列表
    "allowSyntheticDefaultImports": true,  // 允许从没有设置默认导出的模块中默认导入。

    /* Source Map Options */
    "sourceRoot": "./",                    // 指定调试器应该找到 TypeScript 文件而不是源文件的位置
    "mapRoot": "./",                       // 指定调试器应该找到映射文件而不是生成文件的位置
    "inlineSourceMap": true,               // 生成单个 soucemaps 文件,而不是将 sourcemaps 生成不同的文件
    "inlineSources": true,                 // 将代码与 sourcemaps 生成到一个文件中,要求同时设置了 --inlineSourceMap 或 --sourceMap 属性

    /* 其他选项 */
    "experimentalDecorators": true,        // 启用装饰器
    "emitDecoratorMetadata": true          // 为装饰器提供元数据的支持
  }
}

TypeScript 编译

在使用 tsconfig.json 时从命令行手动运行 TypeScript 编译器,你可以通过以下方式:

  • 运行 tsc,它会在当前目录或者是父级目录寻找 tsconfig.json 文件。
  • 运行tsc -p ./path-to-project-directory。当然,这个路径可以是绝对路径,也可以是相对于当前目录的相对路径。
  • 你甚至可以使用 tsc -w来启用 TypeScript 编译器的观测模式,在检测到文件改动之后,它将重新编译。

指定文件

{
    
    
  "files": [
    "./some/file.ts"
  ]
}
// 你还可以使用 include 和 exclude 选项来指定需要包含的文件和排除的文件:
{
    
    
  "include": [
    "./folder"
  ],
  "exclude": [
    "./folder/**/*.spec.ts",
    "./folder/someSubFolder"
  ]
}
//注意
//使用 globs:**/* (一个示例用法:some/folder/**/*)意味着匹配所有的文件夹和所有文件(扩展名为 .ts/.tsx,当开启了 allowJs: true 选项时,扩展名可以是 .js/.jsx)。

声明空间

在 TypeScript 里存在两种声明空间:类型声明空间与变量声明空间。ts有了类型的声明和变量的声明那么就可以对静态类型检查

类型声明空间

  • 类型声明空间包含用来当做类型注解的内容,例如下面的类型声明:
class Foo {
    
    }
interface Bar {
    
    }
type Bas = {
    
    };
  • 你可以将 Foo, Bar, Bas 作为类型注解使用,示例如下:
let foo: Foo;
let bar: Bar;
let bas: Bas;
  • 注意,尽管你定义了 interface Bar,却并不能够把它作为一个变量来使用,因为它没有定义在变量声明空间中。
interface Bar {
    
    }
// 出现错误提示: cannot find name 'Bar' 的原因是名称 Bar 并未定义在变量声明空间。
const bar = Bar; // Error: "cannot find name 'Bar'"

变量声明空间

变量声明空间包含可用作变量的内容,在上文中 Class Foo 提供了一个类型 Foo 到类型声明空间,此外它同样提供了一个变量 Foo 到变量声明空间,如下所示:

class Foo {
    
    }
const someVar = Foo;
const someOtherVar = 123;
// interface 定义的内容当作变量使用。

模块

模块分为全局模块、文件模块,全局模块使用较少,因为它会与文件内的代码命名冲突。推荐使用文件模块。

全局模块

  • 在默认情况下,当你开始在一个新的 TypeScript 文件中写下代码时,它处于全局命名空间中。如果你在相同的项目里创建了一个新的文件 bar.ts,TypeScript 类型系统将会允许你使用变量 foo,就好像它在全局可用一样。

文件模块(外部模块)

  • 使用ES6语法
    • 使用 export 关键字导出一个变量或类型
    // foo.ts
    export const someVar = 123;
    export type someType = {
          
          
      foo: string;
    };
    
    • export 的写法除了上面这种,还有另外一种:
    	// foo.ts
    const someVar = 123;
    type someType = {
          
          
      type: string;
    };
    
    export {
          
           someVar, someType };
    
    • 别名导出
    // foo.ts
    const someVar = 123;
    export {
          
           someVar as aDifferentName };
    
    • 解构
    // bar.ts
    import {
          
           someVar, someType } from './foo';
    
    • 别名导入
    // bar.ts
    import {
          
           someVar as aDifferentName } from './foo';
    
    • 除了指定加载某个输出值,还可以使用整体加载,即用星号(*)指定一个对象,所有输出值都加载在这个对象上面:
    // bar.ts
    import * as foo from './foo';
    // 你可以使用 `foo.someVar` 和 `foo.someType` 以及其他任何从 `foo` 导出的变量或者类型
    
    • 只导入模块:
    import 'core-js'; // 一个普通的 polyfill 库
    
    • 从其他模块导入后整体导出:
    export * from './foo';
    
    • 从其他模块导入后,部分导出:
    export {
          
           someVar } from './foo';
    
    • 通过重命名,部分导出从另一个模块导入的项目:
    export {
          
           someVar as aDifferentName } from './foo';
    
    • 默认导入/导出
    // some var
    export default (someVar = 123);
    
    // some function
    export default function someFunction() {
          
          }
    
    // some class
    export default class someClass {
          
          }
    
    // 导入
    import someLocalNameForThisFile from './foo';
    

命名空间

  • 回顾js闭包自执行函数形成局部变量
	(function(something) {
    
    
	  something.foo = 123;
	})(something || (something = {
    
    }));

// 在确保创建的变量不会泄漏至全局命名空间时,这种方式在 JavaScript 中很常见。
// 当基于文件模块使用时,你无须担心这点,但是该模式仍然适用于一组函数的逻辑分组。
// 因此 TypeScript 提供了 namespace 关键字来描述这种分组,如下所示。
	namespace Utility {
    
    
	  export function log(msg) {
    
    
	    console.log(msg);
	  }
	  export function error(msg) {
    
    
	    console.log(msg);
	  }
	}
	
	// usage
	Utility.log('Call me');
	Utility.error('maybe');

值得注意的一点是,命名空间是支持嵌套的。因此,你可以做一些类似于在 Utility 命名空间下嵌套一个命名空间 Messaging 的事情。 对于大多数项目,我们建议使用外部模块和命名空间,来快速演示和移植旧的 JavaScript 代码。

动态导入表达式

异步加载模块

  • webpack bundler 有一个 Code Splitting 功能,它能允许你将代码拆分为许多块,这些块在将来可被异步下载。因此,你可以在程序中首先提供一个最小的程序启动包,并在将来异步加载其他模块。
  • 配合使用webpack实现异步加载,在下面的代码中,进行懒加载 moment 库,同时使用代码分割的功能,这意味 moment 会被分割到一个单独的 JavaScript 文件,当它被使用时,会被异步加载。
import(/* webpackChunkName: "momentjs" */ 'moment')
  .then(moment => {
    
    
    // 懒加载的模块拥有所有的类型,并且能够按期工作
    // 类型检查会工作,代码引用也会工作  :100:
    const time = moment().format();
    console.log('TypeScript >= 2.4.0 Dynamic Import Expression:');
    console.log(time);
  })
  .catch(err => {
    
    
    console.log('Failed to load moment', err);
  });

这是 tsconfig.json 的配置文件:

{
    
    
  "compilerOptions": {
    
    
    "target": "es5",
    "module": "esnext",
    "lib": [
      "dom",
      "es5",
      "scripthost",
      "es2015.promise"
    ],
    "jsx": "react",
    "declaration": false,
    "sourceMap": true,
    "outDir": "./dist/js",
    "strict": true,
    "moduleResolution": "node",
    "typeRoots": [
      "./node_modules/@types"
    ],
    "types": [
      "node",
      "react",
      "react-dom"
    ]
  }
}

おすすめ

転載: blog.csdn.net/shadowfall/article/details/120786972
おすすめ