下面给你整理一份 TypeScript export 用法详解,包含基础导出、默认导出、命名导出、多模块导出、接口/类型导出以及实际项目示例,帮助你全面掌握 TypeScript 模块化。


1️⃣ 基础概念

在 TypeScript(和 ES6)中,export 用于 将模块中的变量、函数、类、接口、类型等导出,方便在其他模块中 import 使用。

TypeScript 模块化与 ES6 完全兼容,但增加了 接口和类型的导出


2️⃣ 命名导出(Named Export)

// math.ts
export const PI = 3.14159;

export function add(a: number, b: number): number {
  return a + b;
}

export class Circle {
  constructor(public radius: number) {}
  area(): number {
    return PI * this.radius ** 2;
  }
}

导入方式

// app.ts
import { PI, add, Circle } from './math';

console.log(PI);
console.log(add(2, 3));

const c = new Circle(5);
console.log(c.area());

✅ 特点:

  • 可导出多个成员
  • 导入时必须使用相同名字(可用 as 重命名)

3️⃣ 默认导出(Default Export)

// logger.ts
export default function log(message: string) {
  console.log(message);
}

导入方式

import log from './logger';

log('Hello TypeScript!');

✅ 特点:

  • 每个模块只能有一个默认导出
  • 导入时可以随意命名

4️⃣ 混合导出(Named + Default)

// utils.ts
export const sum = (a: number, b: number) => a + b;
export const multiply = (a: number, b: number) => a * b;

export default function log(msg: string) {
  console.log(msg);
}

导入方式

import log, { sum, multiply } from './utils';

log('Logging...');
console.log(sum(2,3));
console.log(multiply(2,3));


5️⃣ 导出接口和类型

TypeScript 特有,可以导出接口(interface)、类型别名(type):

// types.ts
export interface User {
  id: number;
  name: string;
}

export type ID = number | string;

导入方式

import { User, ID } from './types';

const user: User = { id: 1, name: 'Alice' };
const uid: ID = 'abc123';

✅ 特点:

  • 接口和类型只在编译阶段存在
  • 不会生成运行时代码

6️⃣ 重新导出(Re-export)

如果你想统一导出多个模块:

// index.ts
export * from './math';
export { default as log } from './logger';
export * from './types';

导入方式

import { PI, add, User } from './index';
import { log } from './index';

log('统一导出测试');

✅ 优势:

  • 创建模块 入口文件(barrel file)
  • 简化导入路径

7️⃣ 其他高级用法

7.1 重命名导出

export { add as addition, multiply as mul } from './utils';

  • 导入时使用重命名后的名字:
import { addition, mul } from './utils';

7.2 导出时定义类型

export type Callback = (result: string) => void;

7.3 导出常量枚举

export enum Status {
  SUCCESS,
  FAIL,
}


8️⃣ 小结

导出方式示例特点
命名导出export const a = 1可导出多个,导入需一致
默认导出export default function(){}每个模块一个,导入可任意命名
接口/类型导出export interface User {}编译时存在,不生成运行时代码
重新导出export * from './mod'创建统一入口,简化导入
重命名导出export { a as b }导入时使用新名字