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!";
};