CommonJS
As with AMD format, CommonJS (also known as CJS) is another format which defines JavaScript modules as objects that can be made available to any dependent code. CJS modules can only define objects, as opposed to AMD modules, which can define constructors and functions too.
Unlike AMD format, which takes a browser-first approach, CommonJS takes a server-first approach. It also covers a broader set of concerns which are server-related, such as io, file system, and alike.
Many developers (I'm one of them) use AMD format for browser-targeted modules and CommonJS for server-side targeted modules. However, you could use CJS format for browser modules as well.
Some of the tools that support CJS for the browsers are:
curl.js: http://github.com/unscriptable/curl
SproutCore: http://sproutcore.com
Let's have a look at a simple example to see how we can implement a CJS format module.
Implementing a CommonJS module
Imagine that we have a file called moduleOne.js
. From inside this file, we can export...