在 Node.js 中,模块化是一种重要的编程概念,用于组织和管理代码。Node.js 支持两种模块化的标准:CommonJS 和 ECMAScript(ES)模块。

  1. CommonJS 模块化:
  • CommonJS 是 Node.js 最早引入的模块化标准。
  • 在 CommonJS 中,每个文件都是一个模块,并且使用 require 函数导入其他模块,使用 module.exportsexports 导出模块。
  • 例如,导入和导出模块的示例:
// 导入模块
const otherModule = require('./otherModule');

// 导出模块
module.exports = {
  foo: 'bar',
  baz: 123
};
  1. ECMAScript(ES)模块化:
  • ES 模块化是在 ECMAScript 6 (ES6) 规范中引入的官方模块化标准。
  • 在 ES 模块中,使用 import 关键字导入其他模块,使用 export 关键字导出模块。
  • 例如,导入和导出模块的示例:
// 导入模块
import { someFunction } from './otherModule';

// 导出模块
export const foo = 'bar';
export const baz = 123;

在 Node.js 中,默认情况下使用的是 CommonJS 模块化标准。然而,随着 Node.js 的版本升级,ES 模块化也逐渐得到支持。你可以通过使用 .mjs 后缀来使用 ES 模块,或者在 package.json 中的 "type" 字段设置为 "module" 来启用 ES 模块。

请根据你的需求选择适合的模块化标准,并在代码中使用相应的导入和导出语法。