CommonJS - Node.js
CommonJS 是一种流行的模块化模式,在 Node.js 中使用。
CommonJS 系统以 require()
函数为中心,该函数加载其他模块和 exports
属性,该属性允许模块导出可公开访问的方法。
这是 CommonJS 的一个例子,我们将加载 Lodash 和 Node.js 的 fs
模块:
// Load fs and lodash, we can use them anywhere inside the module
var fs = require("fs"),
_ = require("lodash");
var myPrivateFn = function(param) {
return "Here's what you said: " + param;
};
// Here we export a public `myMethod` that other modules can use
exports.myMethod = function(param) {
return myPrivateFn(param);
};
你还可以使用 module.exports
将函数导出为整个模块:
module.exports = function() {
return "Hello!";
};