Pablo Fernandez
Pablo Fernandez

Reputation: 105220

Make a script work nice with the browser and node (npm)

I have a javascript lib, basically this is how it is structured so far:

var Ns = (function(){
  var that = {};

  // add stuff to 'that'

  return that;
})();

//use Ns.foo() and Ns.bar()

The thing is that now, I wanted the same lib to be available with node and npm. So far this is what I could come up with:

this.Ns = (function(){ //same as previous snippet })()

//use Ns.foo() and Ns.bar()

The problem is that, while this works in the browser, in node I need to do this:

var Ns = require('ns').Ns

Problem: I'd love to be able to do var Ns = require('ns') but in order to do that I have to export this.foo and this.bar which will break the browser inclusion. Ideas?

Upvotes: 1

Views: 340

Answers (2)

David
David

Reputation: 106

Creating a scope is probably the best route to go (so you don't have name collision issues), but an easier way to do this, by polluting the global scope, looks like this:

instead of

var x = require('x');

write

var x = (typeof require !== "undefined") ? require('x') : window;

and similarly, before added to exports, check if that object exists:

if (typeof exports !== "undefined)
  exports.my_func = my_func;

The consequences of this, though, is that in the browser version everything gets dumped into global scope. Also, it assumes that the browser version loads the necessary scripts into the page. Easy to get working on a small scale... but I'm guessing it won't scale well.

Upvotes: 0

Raynos
Raynos

Reputation: 169391

// create local scope.
(function () {

  var myModule = ...

  // check for node module loader
  if (typeof module !== "undefined" && typeof require !== "undefined") {
    module.exports = myModule;
  } else {
    window["name"] = myModule;
  }

})();

Upvotes: 3

Related Questions