(function(require, exports) { "use strict"; // ... exports.x = 21; }).apply({}, typeof require === 'function' ? [require, exports] : [function(g){return function(id){return g[id];};}(this._modules = this._modules || {}), this._modules['example/foo'] = {}]);
Ouch. This is one of many variants of boilerplate hacks that folks are using to get CommonJS modules playing nicely with browsers. The CommonJS list has been sparked by the question of client vs. server, and how to deal with the two worlds.
First, “Mark Miller has posted a recommendation on the TC39 wiki for CommonJS module boilerplate that permits modules to be crafted for use as <script>”.
And, then we have Kris Zyp’s proposal for an asynchronous module definition “based on the ideas from Transport/C and recent changes discussed.”
There seem to by two high order bits:
What is the focus of CommonJS?
The project started as “ServerJS”, and many server side JS folks started discussions. However, then other browser JS lib folk got into the mix. Folks who deeply care about module systems for the client as well as the server.
There are varying degrees of interop here. On the one hand folks want to be able to have the work that “makes Foo a module” work in both contexts. But further down we run into issues like: how does legacy code work? Do you have to wrap it? How? And finally, the browser needs to be able to load code asynchronously whereas the server doesn’t have the same issue.
Node is taking off like wild fire. Should Ryan be stopping to think about the browser? Does he really care? Or is he more focused on making a great event driven server environment that uses JavaScript?
What common libraries should we be creating as part of the “SDK” of JavaScript so to speak?
How do we hack on support :/
When we get into the “how” it gets messy quick. Messy can be hand-waved away if you assume that everyone will be using build tools and the like, but a ground swell of comments have been about the developer ergonomics of working on projects. How is it to debug and write applications? Do you get the basics: correct line numbers, no need to run builds all the time, etc? And then there is the performance aspect of the final production code.
All of this has just shown me how desperately we need a first class concept of a module beyond the client-esque “script” and function wrappers. Could you imagine showing the apply()
code from above to a Java programmer? “Erm, you can’t just import?”
ES4 tried to give us programming units, packages, and namespaces. How about ES.next giving us one simple system to get us out of this CommonJS mess?