Writing Javascript that runs in multiple environments (with a one-liner)

With the introduction of server-side javascript, it’s nice to be able to utilise any Javascript libraries you may write in both the browser and on the server. I’ve seen a few different approaches to this but wanted a one-liner that I could just stick at the top of an anonymous function… this is what I came up with:


(function() {
  var MyLib = (typeof exports !== 'undefined') ? exports : this.MyLib = {};

  // MyLib.myFunction = ...
}());

Now in NodeJS you can do:


var MyLib = require('./mylib.js');

This also passes JS Lint using the following:


/*jslint */
/*global exports */
(function () {
    "use strict";
    var MyLib = (typeof exports !== 'undefined') ? exports : this.MyLib = {};

    MyLib.foo = 'bar';
}());