语法都正确,但导出方式不同,导入方式也不同,尤其在React和懒加载中区别很大
🆚对比讲解
写法 | 类型 | 导入方式 | 用在 React.lazy? |
---|---|---|---|
export default function MyComponent() |
默认导出 | import MyComponent from './MyComponent' |
✅ 可以直接用 |
export function MyComponent() |
具名导出 | import { MyComponent } from './MyComponent' |
❌ 不能直接用 (除非包 .then() ) |
导入时别名区别
导出类型 | 导入时能重命名吗? | 示例 |
---|---|---|
默认导出 | ✅ 可以随便命名 | import A from '...' |
具名导出 | ✅ 使用 as |
import { X as Y } from '...' |
✅ 1. export default function MyComponent() { ... }
- 这是默认导出。
- 每个模块只能有一个默认导出。
- 用法简单,适合 React 组件默认输出。
js
// MyComponent.js
export default function MyComponent() {
return <div>你好</div>;
}
导入方式:
js
import MyComponent from './MyComponent';
用于懒加载:
js
const MyComponent = React.lazy(() => import('./MyComponent')); // ✅ 直接用
✅ 2. export function MyComponent() { ... }
- 这是具名导出。
- 一个文件可以导出多个具名变量或函数。
- 更灵活,但懒加载时要做额外处理。
js
// MyComponent.js
export function MyComponent() {
return <div>你好</div>;
}
导入方式:
js
import { MyComponent } from './MyComponent';
如果你要懒加载这个具名导出组件,需要手动指定 default:
js
const MyComponent = React.lazy(() =>
import('./MyComponent').then(module => ({ default: module.MyComponent }))
); // ✅ 可以,但稍麻烦
什么时候用哪个?
场景 | 推荐用法 |
---|---|
单个 React 组件一个文件 | export default (更常见) |
多个工具函数 / 多个组件一起导出 | export { A, B } (具名导出) |
想用 React.lazy 简化写法 | export default 更方便 |