Idiot Note: CommonJS

Javascript is a complicated language, to say the least. There's so many problems or concepts that are exclusive to this language. In this Note, I want to look into one particular thing, which is CommonJS. Just as a brief intro.

History

In January 2009, Kevin Dangoor wrote an article that pointed out the lack of useful ecosystem in server-side Javascript development. He pointed out some aspects that are missing from Javascript at the time:
  1. Cross-interpreter standard library
  2. Standard Interfaces
  3. A standard way to include modules
  4. A convenient way to package up a code for deployment and distribution (for Windows and Macs users)
  5. An easy way to distribute and install packages
Then, the project was initiated. It was initially called ServerJS. In March 2009, CommonJS API 0.1 was created. In April 2009, CommonJS modules were shown off at the first JSConf, Javascript Community Conference. And in August 2009, it was officially renamed to CommonJS.

Modules

Before CommonJS existed, writing Javascript is generally done by using <script> tags. This is okay for client-side code, but not for the server-side's as they are generally more complex. So, the first specification (version 1.0) for CommonJS proposed the use of modules. By using modules, there will no longer be global variables/functions that you usually have when using <script> tags. Instead, you'll have namespaced modules that will be easier to be imported or exported. This specification proposed the keywords "require" and "exports" as the only means of exporting and importing modules.
For example:
concat.js
exports.concat = function(str1, str2) {
    return str1 + ' ' + str2;
}
main.js
var con = require('concat').concat;
con('hello', 'world!') // 'hello world!'
Then, this specification was detailed even further twice (version 1.1 and version 1.1.1). But, the core concept is still the same.
 
Aand, that's the story of how we get this standard modular system which is used by many newer frameworks, such as Node and MongoDB. Thanks to the initiative of CommonJS project.

P.S.

Besides modules, there are a lot of other things that CommonJS offered. Check it here if you're interested.