When creating AMD modules you can export whatever you like whether it be an object or a function. I vaguely recall reading a recommendation somewhere to export just one thing; the idea being “keep it small.”
Using this philosophy means that one might go as far as to export single functions. And when this is coupled with the idea of composition, one will very likely use one function to build up another function. As a result, when loading a page that uses a highly-composed function one might end up asynchronously downloading a handful of little modules in order to build up a composed function.
Take underscore.js which has many functions built in. There are web pages where I just need one or two of it’s functions but I find myself a little at odds with pulling the whole library in as a module just for that. I am half tempted to rewrite the one or two functions to avoid that, but that goes against the idea of reuse. Still, because underscore has several dozen function, pulling it down with an AMD loader like RequireJS is often going to mean pulling down more than necessary. If one goes to the other extreme, decomposing a library like underscore into single function modules, one can run into the aforementioned issue of pulling a couple couple handfuls of tiny modules when highly-composed functions are needed.
So what’s the verdict? How does one draw the line when deciding how much to export from an AMD module? A function is the smallest composable unit. An object that gets exported is often really a namespace which offers a suite a functions, many of which won’t get used.
I searched online for discussions surrounding this, but apparently I couldn’t find the right search terms to locate them. If you’re aware of any, please include any links where this has been discussed to support your answer.
3
Don’t worry about your exports being too fine-grained or too broad. This is what we have build-time tools for.
If you want to export many small modules (or individual functions), we have tools like RequireJS Optimizer to merge everything into a single resource. If you want to export a large namespace object with some functions that may be unused, we have tools like Closure Compiler to remove the dead code.
Organize your modules in a way you are comfortable with and have each individual script export whatever it needs to export. Let the tooling handle the rest.
Also note that while AMD allows multiple define
s in a single source file, via explicitly named modules, this is not recommended. Each source file should only define a single module, and it should be anonymous. Named modules are only intended for use in a compiled script, such as those produced by Optimizer.
2