Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where are the CommonJS modules?

From time to time I hear that CommonJS http://www.commonjs.org/ is an effort to create a set of modular javascript components but frankly I have never understood anything of it.

Where are the these modular components I can use? I don't see much on their homepage.

like image 626
ajsie Avatar asked Nov 25 '10 23:11

ajsie


2 Answers

CommonJS is only a standard that specifies a way to modularize JavaScript, so CommonJS itself does not provide any JavaScript libraries.

CommonJS specifies a require() function which lets one import the modules and then use them, the modules have a special global variable named exports which is an object which holds the things that will get exported.

// foo.js ---------------- Example Foo module
function Foo() {
    this.bla = function() {
        console.log('Hello World');
    }
}

exports.foo = Foo;

// myawesomeprogram.js ----------------------
var foo = require('./foo'); // './' will require the module relative
                            // in this case foo.js is in the same directory as this .js file
var test = new foo.Foo();
test.bla(); // logs 'Hello World'

The Node.js standard library and all 3rd party libraries use CommonJS to modularize their code.

One more example:

// require the http module from the standard library
var http = require('http'); // no './' will look up the require paths to find the module
var express = require('express'); // require the express.js framework (needs to be installed)
like image 51
Ivo Wetzel Avatar answered Oct 19 '22 10:10

Ivo Wetzel


The idea, it seems (I wasn't aware of this), is to provide javascript to more than just web browsers. For example, CouchDB supports javascript for querying.

like image 39
cambraca Avatar answered Oct 19 '22 09:10

cambraca