Question

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.

Was it helpful?

Solution

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)

OTHER TIPS

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.

CommonJS is NOT A MODULE its just a specification which defines how two JavaScript modules should communicate with each other. This specification uses exports variable and require function to define how the modules will expose and consume each other.

To implement CommonJS spec we have lot of open source JS frameworks who follow CommonJS spec. Some examples of JS loaders are systemJS, Webpack , RequireJS and so on. Below is a simple video which explains CommonJS and it also demonstrates how systemJS implements common js spec.

Common JS video :- https://www.youtube.com/watch?v=jN4IM5tp1SE

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top