返回

一文搞懂 export、exports、modules.exports 和 require 、import

前端

<!--文章-->


## 简介

在现代 JavaScript 开发中,模块化编程是一种常见的实践。它允许你将代码组织成更小的、可重用的块,从而提高代码的可维护性和可读性。在 JavaScript 中,有两种主要的模块化编程系统:CommonJS 和 ES modules。

CommonJS 是一个较早的模块化编程系统,它使用 `require()` 和 `module.exports` 语法来导出和导入模块。ES modules 是一个较新的模块化编程系统,它使用 `import` 和 `export` 语法来导出和导入模块。

## 功能区别

| 功能 | require/import | export/exports/modules.exports |
|---|---|---|
| 引用功能 | require、import | - |
| 导出功能 | - | export、exports、module.exports |

### 引用功能

`require()` 和 `import` 都用于引用其他模块。`require()` 用于引用 CommonJS 模块,而 `import` 用于引用 ES modules。

### 导出功能

`export`、`exports` 和 `modules.exports` 都用于导出模块。`export` 用于导出 ES modules,而 `exports` 和 `modules.exports` 用于导出 CommonJS 模块。

## 使用场景

### CommonJS

CommonJS 模块化编程系统通常用于 Node.js 开发。在 Node.js 中,你可以使用 `require()` 语法来引用其他模块,并使用 `module.exports` 语法来导出模块。

```javascript
// 导出模块
module.exports = function() {
  console.log('Hello, world!');
};

// 引用模块
const hello = require('./hello');

hello(); // 输出: Hello, world!
```

### ES modules

ES modules 模块化编程系统通常用于浏览器开发。在浏览器中,你可以使用 `import` 语法来引用其他模块,并使用 `export` 语法来导出模块。

```javascript
// 导出模块
export function hello() {
  console.log('Hello, world!');
}

// 引用模块
import { hello } from './hello';

hello(); // 输出: Hello, world!
```

## 总结

`require()` 和 `import` 都是用于引用其他模块的语法。`require()` 用于引用 CommonJS 模块,而 `import` 用于引用 ES modules。

`export`、`exports` 和 `modules.exports` 都用于导出模块。`export` 用于导出 ES modules,而 `exports` 和 `modules.exports` 用于导出 CommonJS 模块。