面试题答案
一键面试方式一:默认导出与导入
- 导出:在
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;
- 导入:在其他文件中,可以这样导入默认导出的模块:
import add from './index';
const result = add(2, 3);
console.log(result);
方式二:命名导出与导入
- 导出:在
index.ts
中,将多个模块进行命名导出。例如,有mathUtils.ts
文件包含add
和subtract
函数:
// 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 };
- 导入:在其他文件中,使用大括号进行命名导入:
import { add, subtract } from './index';
const addResult = add(5, 3);
const subtractResult = subtract(5, 3);
console.log(addResult, subtractResult);
方式三:重新导出
- 导出:直接在
index.ts
中重新导出模块,无需先导入到本地。例如,对于mathUtils.ts
:
// mathUtils.ts
export const multiply = (a: number, b: number) => a * b;
在 index.ts
中:
export * from './mathUtils';
- 导入:在其他文件中:
import { multiply } from './index';
const multiplyResult = multiply(4, 3);
console.log(multiplyResult);