nodejs有几种模块模式
在 Node.js 或前端 JavaScript 中,除了 ES Module(ESM) 模块系统外,主要还有以下几种模块模式👇
🧩 一、CommonJS(CJS)
✅ Node.js 默认模块系统(直到 ES Module 出现前)
- 使用 require()导入模块
- 使用 module.exports或exports导出模块
- 同步加载模块(在执行时加载)
示例:
// math.js
module.exports = {add: (a, b) => a + b
}// main.js
const math = require('./math')
console.log(math.add(2, 3))  // 5
特点:
- Node.js 原生支持
- 文件扩展名一般是 .js
- 适合服务端开发
- 无法在浏览器中直接使用(需打包)
🧩 二、ES Module(ESM)
✅ 现代模块系统(ES6 引入)
- 使用 import/export语法
- 静态分析模块依赖(编译阶段加载)
- 异步加载(支持 import()动态导入)
示例:
// math.mjs
export function 