MST

星途 面试题库

面试题:TypeScript 中 import 和 export 常见用法

请详细说明在 TypeScript 中使用 export 导出模块成员的几种方式,并分别举例。同时阐述 import 导入这些成员时对应的语法。
40.5万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试

1. 导出单个成员

  • 导出方式:在定义成员(如变量、函数、类等)前直接使用 export 关键字。
    • 示例
// utils.ts
export const add = (a: number, b: number) => a + b;
  • 导入语法:使用 import {成员名} from '模块路径';
    • 示例
import {add} from './utils';
console.log(add(1, 2)); 

2. 导出多个成员

  • 导出方式:可以在多个成员定义前分别使用 export 关键字,也可以使用一个 export 语句导出多个成员。
    • 分别导出示例
// mathUtils.ts
export const subtract = (a: number, b: number) => a - b;
export const multiply = (a: number, b: number) => a * b;
  • 集中导出示例
// mathUtils.ts
const subtract = (a: number, b: number) => a - b;
const multiply = (a: number, b: number) => a * b;
export {subtract, multiply};
  • 导入语法:使用 import {成员名1, 成员名2} from '模块路径';
    • 示例
import {subtract, multiply} from './mathUtils';
console.log(subtract(5, 3)); 
console.log(multiply(2, 4)); 

3. 重命名导出

  • 导出方式:在 export 时使用 as 关键字对成员进行重命名。
    • 示例
// stringUtils.ts
const formatString = (str: string) => str.toUpperCase();
export {formatString as format};
  • 导入语法:按照重命名后的名称导入,import {重命名后的成员名} from '模块路径';
    • 示例
import {format} from './stringUtils';
console.log(format('hello')); 

4. 默认导出

  • 导出方式:使用 export default 关键字,一个模块只能有一个默认导出。
    • 示例
// greeting.ts
const greet = (name: string) => `Hello, ${name}!`;
export default greet;
  • 导入语法:使用 import 自定义名称 from '模块路径';,自定义名称可随意取。
    • 示例
import sayHello from './greeting';
console.log(sayHello('John')); 

5. 整体导入导出(重新导出)

  • 导出方式:使用 export * from '模块路径';,将其他模块的所有导出成员重新导出。
    • 示例:假设已有 mathUtils.ts 文件,内容如上述导出多个成员部分。
// allMath.ts
export * from './mathUtils';
  • 导入语法:和正常导入原模块一样,如 import {成员名} from './allMath';
    • 示例
import {subtract} from './allMath';
console.log(subtract(10, 5));