本文发表于 668 天前,其中的信息可能已经事过境迁
文章摘要
加载中...|
此内容根据文章生成,并经过人工审核,仅用于文章内容的解释与总结 投诉

一、tsconfig.json 配置

bash
# tsconfig.json文件可以通过下面的命令生成
tsc --init

配置详解

json
"compilerOptions": {
  "incremental": true, // TS编译器在第一次编译之后会生成一个存储编译信息的文件,第二次编译会在第一次的基础上进行增量编译,可以提高编译的速度
  "tsBuildInfoFile": "./buildFile", // 增量编译文件的存储位置
  "diagnostics": true, // 打印诊断信息
  "target": "ES5", // 目标语言的版本
  "module": "CommonJS", // 生成代码的模板标准
  "outFile": "./app.js", // 将多个相互依赖的文件生成一个文件,可以用在AMD模块中,即开启时应设置"module": "AMD",
  "lib": ["DOM", "ES2015", "ScriptHost", "ES2019.Array"], // TS需要引用的库,即声明文件,es5 默认引用dom、es5、scripthost,如需要使用es的高级版本特性,通常都需要配置,如es8的数组新特性需要引入"ES2019.Array",
  "allowJS": true, // 允许编译器编译JS,JSX文件
  "checkJs": true, // 允许在JS文件中报错,通常与allowJS一起使用
  "outDir": "./dist", // 指定输出目录
  "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": [], // 加载的声明文件包
  "removeComments":true, // 删除注释
  "noEmit": true, // 不输出文件,即编译后不会生成任何js文件
  "noEmitOnError": true, // 发送错误时不输出任何文件
  "noEmitHelpers": true, // 不生成helper函数,减小体积,需要额外安装,常配合importHelpers一起使用
  "importHelpers": true, // 通过tslib引入helper函数,文件必须是模块
  "downlevelIteration": true, // 降级遍历器实现,如果目标源是es3/5,那么遍历器会有降级的实现
  "strict": true, // 开启所有严格的类型检查
  "alwaysStrict": true, // 在代码中注入'use strict'
  "noImplicitAny": true, // 不允许隐式的any类型
  "strictNullChecks": true, // 不允许把null、undefined赋值给其他类型的变量
  "strictFunctionTypes": true, // 不允许函数参数双向协变
  "strictPropertyInitialization": true, // 类的实例属性必须初始化
  "strictBindCallApply": true, // 严格的bind/call/apply检查
  "noImplicitThis": true, // 不允许this有隐式的any类型
  "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// 打印编译的文件(包括引用的声明文件)
}

// 指定一个匹配列表(属于自动指定该路径下的所有ts相关文件)
"include": [
   "src/**/*"
],
// 指定一个排除列表(include的反向操作)
 "exclude": [
   "demo.ts"
],
// 指定哪些文件使用该配置(属于手动一个个指定文件)
 "files": [
   "demo.ts"
]

常用配置

include指定编译文件默认是编译当前目录下所有的 ts 文件
exclude指定排除的文件
target指定 js 编译的版本 ES5 ES6
allowJS是否允许编译 JS
removeComments是否在编译的过程中删除注释
rootDir编译文件的目录
outDir输出目录
sourceMap源代码映射
strict严格模式
module模块规范 如 commonjs es6 amd umd 等

二、命名空间 namespace

  • 内部模块,主要用于组织代码,避免命名冲突。
  • 命名空间内的类默认私有
  • 通过 export 暴露
  • 通过 namespace 关键字定义

命名空间中通过 export 将想要暴露的部分导出

如果不用 export 导出是无法读取其值的

ts
namespace a {
  export const Time: number = 1000;
  export const fn = <T>(arg: T): T => {
    return arg;
  };
  fn(Time);
}

namespace b {
  export const Time: number = 1000;
  export const fn = <T>(arg: T): T => {
    return arg;
  };
  fn(Time);
}

a.Time;
b.Time;

嵌套命名空间

ts
namespace a {
  export namespace b {
    export class Vue {
      parameters: string;
      constructor(parameters: string) {
        this.parameters = parameters;
      }
    }
  }
}

let v = a.b.Vue;

new v("1");

抽离命名空间

ts
// a.ts

export namespace V {
  export const a = 1;
}

// b.ts

import { V } from "../observer/index";

console.log(V);
//{a:1}

简化命名空间

ts
namespace A {
  export namespace B {
    export const C = 1;
  }
}

import X = A.B.C;

console.log(X);

合并命名空间

重名的命名空间会合并

三、模块解析

多种多样的模块化

前端模块化规范有很多种,在 ES6 的 ES Module 模块化规范出来前,有许多社区版本的模块化

例如:

  • 大名鼎鼎的 CommonJS
  • AMD
  • CMD
  • UMD

ES Module 出现之后上述模块化规范就少了很多,基本上只有 ES Module 和 CommonJS(Node.js) 在用了,推荐到 MDN 去看看官方的具体描述

MDN modules :https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Guide/Modules

四、声明文件(xxx.d.ts)

声明文件 declare

当使用第三方库时,我们需要引用它的声明文件,才能获得对应的代码补全、接口提示等功能。

ts
declare var 声明全局变量
declare function 声明全局方法
declare class 声明全局类
declare enum 声明全局枚举类型
declare namespace 声明含有子属性的全局对象
interface type 声明全局类型
/// <reference /> 三斜线指令

当我们在 ts 项目中安装一些第三方库时,发现发生了类型报错,大概率是我们没有它的声明文件导致的

例如:安装了 express 三方库报错,提示找不到声明文件,那么这时我们就要去安装一下,运行以下 npm 命令:

bash
npm i -D @types/node

手写声明文件

假设这是我们使用到的一些 express 提供的 API index.ts

ts
import express from "express";

const app = express();

const router = express.Router();

app.use("/api", router);

router.get("/list", (req, res) => {
  res.json({
    code: 200,
  });
});

app.listen(9001, () => {
  console.log(9001);
});

那么它涉及到的声明文件为 express.d.ts

ts
declare module "express" {
  interface Router {
    get(path: string, cb: (req: any, res: any) => void): void;
  }
  interface App {
    use(path: string, router: any): void;
    listen(port: number, cb?: () => void): void;
  }
  interface Express {
    (): App;
    Router(): Router;
  }
  const express: Express;
  export default express;
}
赞赏博主
评论 隐私政策