Modules are mostly the same in Node.js and AMD [1]: A sequence of statements that assign internal values to variables and exported values to an object. This blog post shows several patterns for doing the latter. It also explains how ECMAScript.next handles exports.
exports.value1 = ...;In an AMD, you return an object:
define(function () { // no imports return { value1: ... }; });
function funcInternal(...) { ... } var e = { otherFuncExported: ..., funcExported: function (...) { funcInternal(...); e.otherFuncExported(...); } }; module.exports = e; // AMD: return e;Pro and cons:
var e = exports; // AMD: var e = {}; e.otherFuncExported = ...; function funcInternal(...) { ... } e.funcExported = function (...) { funcInternal(...); e.otherFuncExported(...); }; // AMD: return e;Pro and con:
function otherFuncExported() { ... } function funcInternal(...) { ... } function funcExported(...) { funcInternal(...); otherFuncExported(...); }; // AMD: return { module.exports = { otherFuncExported: otherFuncExported, funcExported: funcExported }Pro and con:
var e = exports; // AMD: var e = {}; var otherFuncExported = e.otherFuncExported = function () { ... }; function funcInternal(...) { ... } var funcExported = e.funcExported = function (...) { funcInternal(...); otherFuncExported(...); }; // AMD: return ePro and con:
export function otherFuncExported() { ... } function funcInternal(...) { ... } export function funcExported(...) { funcInternal(...); otherFuncExported(...); };Approach 2: Refer to exported values.
function otherFuncExported() { ... } function funcInternal(...) { ... } function funcExported(...) { funcInternal(...); otherFuncExported(...); }; export otherFuncExported, funcExported;It would be nice if one could emulate the latter approach in current module systems, but there is no way to access the entries of an environment in JavaScript. That would allow one to do the following (using Underscore’s pick() function which clones an object, but only copies the properties whose names are mentioned):
module.exports = _.pick(environmentToObject(), "otherFuncExported", "funcExported" );ECMAScript.next also has a shortcut for object literals that would be useful for current modules:
module.exports = { otherFuncExported, funcExported };Which is syntactic sugar for:
module.exports = { otherFuncExported: otherFuncExported, funcExported: funcExported };