再出口

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