📜  如何在 NodeJS 中使用 EcmaScript 模块?(1)

📅  最后修改于: 2023-12-03 15:24:18.069000             🧑  作者: Mango

如何在 NodeJS 中使用 EcmaScript 模块?

由于 NodeJS 使用的是 CommonJS 模块系统,而非浏览器环境下常用的 ES6 模块系统,因此在 NodeJS 中使用 ES6 模块需要进行一些额外的设置和配置。

1. 版本要求

注意,NodeJS 必须是版本 13.2.0 或更高版本才能使用 ES6 模块。

如果你的 NodeJS 版本不符合要求,可以通过 nvm 工具来进行版本切换。使用方法可参考官方文档:https://github.com/nvm-sh/nvm

2. 修改文件扩展名

ES6 模块的文件扩展名为 .mjs,因此需要将需要使用 ES6 模块的文件后缀名修改为 .mjs。

3. 配置 package.json

为了让 NodeJS 正确地解析 .mjs 文件,需要在 package.json 文件中添加如下内容:

"test": "node --experimental-modules test.mjs"

其中,test.mjs 是需要运行的 .mjs 文件名。

4. 导入和导出模块
4.1 导出模块

ES6 模块的导出方式使用 export 关键字:

export const add = (a, b) => a + b;
export const subtract = (a, b) => a - b;

或者使用 default 关键字:

const multiply = (a, b) => a * b;
export default multiply;
4.2 导入模块

ES6 模块的导入方式使用 import 关键字:

import { add, subtract } from './math.mjs';

或者使用 import * as 关键字:

import * as math from './math.mjs';
console.log(math.add(1, 2)); // 3

或者使用 default 关键字:

import multiply from './math.mjs';
console.log(multiply(2, 3)); // 6
5. 测试

运行 package.json 中配置的命令进行测试:

npm test

如果能够输出正确结果,则说明已经成功地使用了 ES6 模块。

参考链接:

  1. https://nodejs.org/api/esm.html
  2. https://medium.com/@giltayar/native-es-modules-in-nodejs-status-and-future-directions-part-i-ee5ea3001f71