MST
星途 面试题库

面试题:TypeScript中index.ts常见的组织模块方式

在TypeScript项目里,index.ts经常用于组织模块。请描述至少两种在index.ts中常用的组织模块的方式,并举例说明如何通过这些方式来导出和导入模块。
11.8万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试

方式一:默认导出与导入

  1. 导出:在 index.ts 中,使用 export default 导出模块。例如,假设有一个 utils.ts 文件包含一个函数 add
// utils.ts
export const add = (a: number, b: number) => a + b;

index.ts 中:

import { add } from './utils';
export default add;
  1. 导入:在其他文件中,可以这样导入默认导出的模块:
import add from './index';
const result = add(2, 3);
console.log(result); 

方式二:命名导出与导入

  1. 导出:在 index.ts 中,将多个模块进行命名导出。例如,有 mathUtils.ts 文件包含 addsubtract 函数:
// mathUtils.ts
export const add = (a: number, b: number) => a + b;
export const subtract = (a: number, b: number) => a - b;

index.ts 中:

import { add, subtract } from './mathUtils';
export { add, subtract };
  1. 导入:在其他文件中,使用大括号进行命名导入:
import { add, subtract } from './index';
const addResult = add(5, 3);
const subtractResult = subtract(5, 3);
console.log(addResult, subtractResult); 

方式三:重新导出

  1. 导出:直接在 index.ts 中重新导出模块,无需先导入到本地。例如,对于 mathUtils.ts
// mathUtils.ts
export const multiply = (a: number, b: number) => a * b;

index.ts 中:

export * from './mathUtils';
  1. 导入:在其他文件中:
import { multiply } from './index';
const multiplyResult = multiply(4, 3);
console.log(multiplyResult);