1. 程式人生 > 其它 >12 - TS的模組x

12 - TS的模組x

# TS的模組

## 什麼是模組?



模組是一個程式包,包內的成員(函式、變數、型別)僅僅在包內可見,包外想要方位這些成員除非模組自己主動宣告向包外提供。例如用`import/export` 語法。





## Export

向模組外部提供成員



### default Export

```tsx
// @filename : hello.ts
export default function helloWorld() {
console.log("Hello, world!");
}
```

外部引用方式 如下:

```tsx
import hello from './hello.ts'
hello()
```

### non-default export

```tsx
// @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;
}
```

可以這樣引用:

```tsx
import { pi, phi, absolute } from "./maths.js";

console.log(pi, phi);
console.log(absolute(phi))
```



### 別名

為了防止模組衝突,可以使用別名。

```tsx
import { pi as π } from "./maths.js";

console.log(π);
```

### Export型別

```tsx
// @filename: animal.ts
export type Cat = { breed: string; yearOfBirth: number }
export interface Dog {}
```

可以用`import` 或者`import type` 來使用:

```tsx
import {Cat} from './animal.ts'
import type {Cat} from './animal.ts '
```

`import type` 顯示告訴編譯器你只需要型別資訊。

例如:

```tsx
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

# Namespace

這是一個廢棄的能力,目前我們都用`module` 。