面试题答案
一键面试具名导入和默认导入的区别
- 语法差异
- 具名导入:使用花括号
{}
来指定要导入的具体成员,如import { functionName } from './module'
。一个模块可以有多个具名导出,导入时可以按需选择导入其中部分成员。 - 默认导入:直接导入,不使用花括号,如
import functionName from './module'
。一个模块只能有一个默认导出。
- 具名导入:使用花括号
- 导出定义差异
- 具名导出:在模块中使用
export
关键字直接导出成员,例如:
- 具名导出:在模块中使用
export function add(a: number, b: number) {
return a + b;
}
export const PI = 3.14;
- 默认导出:使用
export default
关键字导出一个值,例如:
const message = 'Hello, world!';
export default message;
- 导入灵活性差异
- 具名导入:更灵活,可选择性导入模块中的多个或单个具名成员。比如在一个工具模块中有多个工具函数,可按需导入,像
import { add, subtract } from './mathUtils'
。 - 默认导入:更简洁,适用于模块主要导出一个实体(如一个类、一个函数等)的情况。比如一个模块专门导出一个 Vue 组件,
import MyComponent from './MyComponent.vue'
。
- 具名导入:更灵活,可选择性导入模块中的多个或单个具名成员。比如在一个工具模块中有多个工具函数,可按需导入,像
适用场景举例
- 具名导入适用场景
- 工具模块:当模块提供多个功能函数时,使用具名导入更合适。例如,有一个
stringUtils.ts
模块:
- 工具模块:当模块提供多个功能函数时,使用具名导入更合适。例如,有一个
export function capitalize(str: string) {
return str.charAt(0).toUpperCase() + str.slice(1);
}
export function reverse(str: string) {
return str.split('').reverse().join('');
}
在其他模块中使用时:
import { capitalize, reverse } from './stringUtils';
console.log(capitalize('hello')); // 'Hello'
console.log(reverse('world')); // 'dlrow'
- 默认导入适用场景
- 组件模块:在 Vue 或 React 开发中,一个文件通常定义一个组件,此时默认导入很方便。以 Vue 为例,
Button.vue
组件:
- 组件模块:在 Vue 或 React 开发中,一个文件通常定义一个组件,此时默认导入很方便。以 Vue 为例,
<template>
<button>{{ label }}</button>
</template>
<script lang="ts">
import { defineComponent } from 'vue';
export default defineComponent({
name: 'Button',
data() {
return {
label: 'Click me'
};
}
});
</script>
在父组件中导入:
<template>
<div>
<Button />
</div>
</template>
<script lang="ts">
import Button from './Button.vue';
import { defineComponent } from 'vue';
export default defineComponent({
components: {
Button
}
});
</script>
结合使用具名导出和默认导出
当一个模块中有多个导出时,可以同时使用具名导出和默认导出。例如,在一个 userModule.ts
模块中:
// 默认导出一个类
export default class User {
constructor(public name: string, public age: number) {}
}
// 具名导出一个函数
export function greetUser(user: User) {
return `Hello, ${user.name}! You are ${user.age} years old.`;
}
在其他模块中导入:
import User, { greetUser } from './userModule';
const myUser = new User('John', 30);
console.log(greetUser(myUser)); // 'Hello, John! You are 30 years old.'