模块系统(CommonJS & ES Modules)
Node.js 支持两种模块系统:CommonJS 和 ES Modules。
📚 CommonJS
Node.js 默认的模块系统。
导出
// math.js
function add(a, b) {
return a + b;
}
// 方式一:module.exports
module.exports = {
add
};
// 方式二:exports
exports.add = add;导入
// app.js
const { add } = require('./math.js');
// 或
const math = require('./math.js');
console.log(math.add(1, 2));特点
- 同步加载
- 运行时解析
- 适合服务端
🎯 ES Modules
ES6 模块系统,需要配置启用。
启用 ES Modules
方式一:package.json
{
"type": "module"
}方式二:文件扩展名
使用 .mjs 扩展名:
// math.mjs
export function add(a, b) {
return a + b;
}导出
// math.js
export function add(a, b) {
return a + b;
}
export default {
multiply(a, b) {
return a * b;
}
};导入
// app.js
import { add } from './math.js';
import math from './math.js';🔄 互操作性
CommonJS 中使用 ES Modules
// 使用动态 import
const math = await import('./math.mjs');ES Modules 中使用 CommonJS
// 可以导入 CommonJS 模块
import math from './math.cjs';💡 选择建议
使用 CommonJS
- 传统 Node.js 项目
- 需要兼容旧版本
- 简单脚本
使用 ES Modules
- 新项目
- 需要 Tree shaking
- 前后端代码共享
🔗 相关链接
- Node.js 简介与特点 — Node.js 概述
- 核心模块 — Node.js 内置模块
- JavaScript 模块化 — JavaScript 模块化详解
参考: