# 前端模块导出知识点

LLMS 索引： [llms.txt](/llms.txt)

---

## ES6 模块化（React / Vue）

### export 和 export default 的区别

#### `export default`（默认导出）

##### 导出文件

通过 `export default` 时，一个文件只能导出一个对象

```js
// a.js 文件
const APP = () => <div> Hello World</div>
export default APP;  // 只能导出一个
```

##### 导入文件

`export default` 只能导出一个对象，所以导入时，导入名称可以随便填写

```js
// b.js 文件
import 随便写 from './a.js'
import MyApp from './a.js'
import Hello from './a.js'
import APP from './a.js'
```

#### `export`（命名导出）

##### 导出文件

```js
// a.js 文件
export const a = 10
export const fn = () => alert('Hello World')
export const user = {name:'JavaScript'}
```

##### 导入文件

```js
// b.js 文件
import { a, fn, user } from './a.js' // 通过 export 导出时，导入时必须用 {}
```

#### 核心总结

- export default 导出，只能导出一个对象，import 导入时可以随便改名，使用场景，主要用于导出组件或者主函数
- export 导出，可以导出多个对象，但是 import 导入时，必须使用 {} 解构，使用场景导出工具函数、多个变量等等。

## NodeJs 模块化（CommonJS）

### module.exports 导出

#### 导出文件

```js
// a.js
const add = (a,b) => a+b

// 默认导出，类似于 ES6 的 export default 导出
module.exports = add
```

#### 导入文件

```js
// b.js
const add = require('./a')
```

#### exports 导出

`exports` 是 `module.exports` 的快捷方式

##### 导出文件

```js
// a.js
let add = (a,b)=>a+b
let sub = (a,b)=>a-b

// exports 导出时，必须具名导出对象，导入时，必须使用 {} 解构
exports.add = add
exports.sub = sub
exports.hello = "Hello World"

// 等价于
module.exports = {
  add, sub, hello: "Hello World"
}
```

##### 导入文件

```js
// b.js
let {add, sub} = require('./a.js') // 通过 exports 导出时，导入必须使用 {}
```

#### 注意点

```js
module.exports = {
    a: 12, b: 25
}

// 不能这么写，exports 导出时，必须具名对象
exports = {
    a: 12, b: 25
}
// 正确写法
exports.hello = {
    a: 12, b: 25
}
```
