再出口

Typescript 允許重新匯出宣告。

//Operator.ts
interface Operator {
    eval(a: number, b: number): number;
}
export default Operator;
//Add.ts
import Operator from "./Operator";
export class Add implements Operator {
    eval(a: number, b: number): number {
        return a + b;
    }
}
//Mul.ts
import Operator from "./Operator";
export class Mul implements Operator {
    eval(a: number, b: number): number {
        return a * b;
    }
}

你可以將所有操作繫結在單個庫中

//Operators.ts
import {Add} from "./Add";
import {Mul} from "./Mul";

export {Add, Mul};

**** 可以使用較短的語法重新匯出命名宣告

//NamedOperators.ts
export {Add} from "./Add";
export {Mul} from "./Mul";

**** 也可以匯出預設匯出,但不提供短語法。請記住,每個模組只能進行一次預設匯出。

//Calculator.ts
export {Add} from "./Add";
export {Mul} from "./Mul";
import Operator from "./Operator";

export default Operator;

可能是重新匯出繫結匯入

//RepackedCalculator.ts
export * from "./Operators";

重新匯出 bundle 時,可以在顯式宣告時覆蓋宣告。

//FixedCalculator.ts
export * from "./Calculator"
import Operator from "./Calculator";
export class Add implements Operator {
    eval(a: number, b: number): number {
        return 42;
    }
}

用法示例

//run.ts
import {Add, Mul} from "./FixedCalculator";

const add = new Add();
const mul = new Mul();

console.log(add.eval(1, 1)); // 42
console.log(mul.eval(3, 4)); // 12