writing js module compatible for node and browser

April 4th, 2013 § 0 comments

This is a simple blog post which will help you to write js modules which is compatible to node and browser.

In this I am writing a module named mylibrary which can used in both node environment and browser environment.

// mylibrary.js
(function(root, factory){
  if(typeof exports == 'object'){
    factory(exports);
  }else{
    root.mylibrary = {};
    factory(root.mylibrary);
  }

}(this,function(exports){
  exports.firstFunction = function(){
    console.log("firstFunction");
  };

  exports.secondFunction = function(){
    console.log("secondFunction");
  };
}));


In mylibrary we have firstFunction and secondFunction as methods.

For browser we can use the methods as

mylibrary.firstFuction();
mylibrary.secondFunction();


In node Environment

var mylibrary = require('mylibrary');
mylibrary.firstFuction();
mylibrary.secondFunction();


Thats it.

Thanks.

Revath S Kumar [RSK]

- Rubyist / JavaScripter - Yeoman Team member - Open source enthusiast - Blogger @ PHPRepo and http://blog.revathskumar.com - Coder @ Whatznear - Google fanboy - jQuery lover

More Posts - Website - Twitter - Facebook - LinkedIn - Pinterest - Google Plus - YouTube

Tagged ,