I want to provide a way to convert existing CommonJS modules as part
of my proposal for an alternate syntax for modules that works well in
the browser and can be hand-authored by devs:
http://wiki.commonjs.org/wiki/AlternateModuleFormatRun
As part of looking at some of the modules, I do not understand some of
the idioms I have seen in some code. I have looked a bit in the
archives, but some of the names involved below are fairly generic and
some of the past discussions are hard to parse out the final needs of
some things. I apologize if some of this is a rehash for you. If it is
helpful, I am happy to update the wiki with any of the answers here,
perhaps as "why" or "motivation" links next to the appropriate places
in any specs.
These questions relate to sections on the Modules 1.1 page:
http://wiki.commonjs.org/wiki/Modules/1.1
Some of the things listed here are listed as "may" items on that page,
so I can appreciate that they are not required by a conforming
implementation, but when I look at trying to convert module syntax,
since they are possible I seem to need to account for them. Most of
the questions for me come down to one basic theme: leaking too much
information about module environment into modules.
1) Module Context, #1,5: The "require" function may have a "main" property:
Why is a main property desirable? At first glance, it seems odd that
modules would want to inspect the ID of the module that is considered
the "main". Knowledge of the entry point into the system seems outside
the scope of a module definition.
2) Module Context, #3: In a module, there must be a free variable "module":
Why is this useful? The one place I have seen it used is to do an
if(require.main ==
module.id) check to then run the equivalent of a
"main" function in the module. However, it seems odd to me that this
is preferred over having a convention that a module exports a main()
function that is called by the system. In short, requiring the module
to bootstrap itself into the main entry point seems like leaking more
environment into the module. Also seems like the module would not have
enough information to execute a "main" function -- the type of "main"
seems to be dependent on the environment (command line args vs. a web
request/response system). Seems like each environment would have their
own conventions on a "main".
3) Not part of Modules 1.1, but I have seen require and require.async
mentioned. This seems to be another instance of how the loading of a
module is done (sync vs async) that seems like it would not be a
primary concern of a module that is specifying dependencies.
James