Search code examples
javascriptnode.jscommonjs

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.


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)