Why not use it as a general component pattern for Javascript, including browser-executed Javascript?
At a glance, it seems to be a good way to modularize the 开发者_运维百科project I'm currently working on, which consists of a large Javascript code-base, with lots of components, some of which interact with eachother.
CommonJS is definitely suitable for the browser, with some caveats. The CommonJS module pattern is quite nice (in my biased opinion), and is also a good stepping stone to the module system proposed for ECMAScript Harmony (the planned next release of the JavaScript language). Specifically, Harmony modules won't have access to the global ("window") object.
The reason that some people claim CommonJS modules are not suitable for the browser is that they can't be loaded via a <script> tag without some server-side assistance. For example, imagine you have a markdown library that exports a "convertToHTML" function. You could then make a module that looks like this:
var convertToHTML = require("markdown").convertToHTML;
exports.mangleSomeText = function() {
// do something then call convertToHTML
}
This doesn't work via a script tag for a few reasons (the scope isn't wrapped, so convertToHTML would get attached to window, require wouldn't typically be defined and exports needs to be created separately for each module).
A client side library with a tiny bit of server side help could allow this to load via script tags easily. Or, a client side library that loads the script via XMLHttpRequest and does an eval() would also work, though the debugging experience is often not as good.
A fairly reasonable solution right now, though one that is also the subject of contentious debate among CommonJS members, is RequireJS. Using RequireJS, you can write your module like this:
define(function(require, exports, module) {
var convertToHTML = require("markdown").convertToHTML;
exports.mangleSomeText = function() {
// do something then call convertToHTML
}
});
All we did was add that define() bit around the module. (You could likely make a server do that pretty easily as well, so that you don't even need to manually type the define part).
I've personally used RequireJS on a couple of projects now and find it an easy way to make use of CommonJS modules without a server-side bit. There are many other solutions and if you aren't reliant on running static JS files, standard CommonJS modules are a great way to go.
(ObDisclaimer: I started the CommonJS project, so I am clearly biased.)
精彩评论