Node.js 模块模式是组织代码结构的核心概念,主要通过 IIFE、CommonJS 和 ES Modules 实现。以下是关键解析:
1. IIFE 模式 (Immediately Invoked Function Expression)
(function() {
// 私有作用域
const privateVar = 'Secret';
const myModule = {
publicMethod() {
return privateVar;
}
};
})();
- 优点:避免全局污染,封装私有变量
- 缺点:难以复用,配置复杂
2. CommonJS 模块
// module.js
exports.myFunction = function() {
return 'CommonJS';
};
// app.js
const module = require('./module.js');
console.log(module.myFunction());
- 适用场景:服务器端(Node.js 原生支持)
- 优势:模块化开发,依赖管理清晰
3. ES Modules (ESM)
// module.mjs
export function myFunction() {
return 'ESM';
}
// app.mjs
import { myFunction } from './module.mjs';
console.log(myFunction());
- 特点:原生支持异步加载,语法更现代化
- 配置:需在
package.json
中设置"type": "module"
扩展阅读
想深入了解模块化实践?可参考 /nodejs_best_practices 了解更高级的编码规范。