面试题答案
一键面试利用ES6的import和export语法实现模块间依赖管理
在TypeScript项目中,ES6的import
和export
语法是实现模块间依赖管理的关键。export
用于将模块内的变量、函数、类等导出,使其可被其他模块使用;import
则用于从其他模块导入所需的内容。
导出一个函数示例
假设有一个名为mathUtils.ts
的文件,其中定义了一个加法函数,并将其导出:
// mathUtils.ts
export function add(a: number, b: number): number {
return a + b;
}
导入一个模块示例
在另一个文件main.ts
中,可以导入mathUtils.ts
模块并使用其中导出的add
函数:
// main.ts
import { add } from './mathUtils';
const result = add(2, 3);
console.log(result); // 输出5
上述代码中,import { add } from './mathUtils';
表示从mathUtils
模块中导入add
函数,路径./
表示当前目录。若要导入整个模块,可使用以下方式:
// main.ts
import * as mathUtils from './mathUtils';
const result = mathUtils.add(2, 3);
console.log(result); // 输出5
这里import * as mathUtils from './mathUtils';
将mathUtils
模块中的所有导出内容都导入,并通过mathUtils
对象来访问其中的函数,如mathUtils.add
。