ExportingImporting 宣告

任何宣告(變數,const,函式,類等)都可以從模組匯出,以便在其他模組中匯入。

Typescript 提供兩種匯出型別:命名和預設。

命名出口

// adams.ts
export function hello(name: string){
    console.log(`Hello ${name}!`);
}
export const answerToLifeTheUniverseAndEverything = 42;
export const unused = 0;

匯入命名匯出時,可以指定要匯入的元素。

import {hello, answerToLifeTheUniverseAndEverything} from "./adams";
hello(answerToLifeTheUniverseAndEverything);   // Hello 42!

預設匯出

每個模組可以有一個預設匯出

// dent.ts
const defaultValue = 54;
export default defaultValue;

可以使用匯入

import dentValue from "./dent";
console.log(dentValue);        // 54

繫結匯入

Typescript 提供了將整個模組匯入變數的方法

// adams.ts
export function hello(name: string){
    console.log(`Hello ${name}!`);
}
export const answerToLifeTheUniverseAndEverything = 42;
import * as Bundle from "./adams";
Bundle.hello(Bundle.answerToLifeTheUniverseAndEverything);  // Hello 42!
console.log(Bundle.unused);                                 // 0