什么是模块?
模块是一个程序包,包内的成员(函数、变量、类型)仅仅在包内可见,包外想要方位这些成员除非模块自己主动声明向包外提供。例如用`import/export` 语法。
Export
向模块外部提供成员
default Export
// @filename : hello.ts
export default function helloWorld() {
console.log("Hello, world!");
}
外部引用方式 如下:
import hello from './hello.ts'
hello()
non-default export
// @filename: maths.ts
export var pi = 3.14;
export let squareTwo = 1.41;
export const phi = 1.61;
export class RandomNumberGenerator {}
export function absolute(num: number) {
if (num < 0) return num * -1;
return num;
}
可以这样引用:
import { pi, phi, absolute } from "./maths.js";
console.log(pi, phi);
console.log(absolute(phi))
别名
为了防止模块冲突,可以使用别名。
import { pi as π } from "./maths.js";
console.log(π);
Export类型
// @filename: animal.ts
export type Cat = { breed: string; yearOfBirth: number }
export interface Dog {}
可以用`import` 或者`import type` 来使用:
import {Cat} from './animal.ts'
import type {Cat} from './animal.ts '
`import type` 显示告诉编译器你只需要类型信息。
import type {Foo} from './animal'
const foo = new Foo()
'Foo' cannot be used as a value because it was imported using 'import type'
TS的模块解析配置项
TS的配置项`module` 可以用来配置TS将模块编译成什么?可选项包括:
- ES6
- ES2015
- ES2020
- UMD
- AMD
- Commonjs
- SYSTEM
- ESNext
等等
另外可以配置`moduleResolution` 项来决定模块的加载算法,可以是:
- node
- classic
1