探秘Typescript·TS中的模块

66 阅读2分钟

探秘Typescript·TS的模块

cover

什么是模块

模块就是一个程序包,包内的成员,包括函数、变量、类型等都仅在包内可见,包外如果想要访问这些成员,除非模块自己主动对外导出,例如使用import/export语法。

Export

向模块外部提供成员,对外导出分为两种形式,默认导出default export和非默认导出non-default export

default export

// file1.ts
export default function add() {
  
}

// file2.ts
import add from './file1.ts';
add();

如上述示例就是默认导出,我们可以直接import对应模块的导出并可以直接使用。

non-default export

// file1.ts
export var a = 1;
export let b = "name";
export const PACKAGE_NAME = "test";
export type Person {
	name: string;
}
export class Student {
  
}
export function add() {
  
}

// file2.ts
import { a, b, PACKAGE_NAME, Student, add } from "./file2.ts";
import type { Person } from "./file2.ts";

如上述示例则是非默认导出和使用的示例。

别名

为了防止模块名之间相互冲突,我们在到处模块时可以指定别名,如:

import { a as customA } from "./file1.ts";
console.log(customA);// 1

类型的导入与导出

Typescript当中,不仅可以导出变量、函数,也可以导入和导出类型

// file1.ts
export type Person {
	name: string;
}
export interface Student {
  
}
export class Car {
  
}

// file2.ts
import { Person, Student, Car } from './file1.ts';
// 使用上述这种方式导入类型的同时,如果该类型同时还是一个类,也会讲该类也导入进来,同时,如果该模块中存在一些自执行的代码,也会在导入时被执行
const car: Car = new Car();// 可以实例化

// file3.ts
import type { Person, Student, Car } from './file1.ts';
// 如果使用 import type 方式引入,则 Typescript 只会帮我们引入类型描述,既不会导入实际代码,也不会导致自执行代码被执行
const car: Car = new Car();// 报错,因为仅仅导入了 Car 的类型,未导入实际执行文件

总结

本质上来说,在Typescript当中,关于模块的导入和导出相关的知识与Javascript当中变化不大,需要注意的就是Typescript当中支持类型的导入和导出。