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';
}());

Published by

Jamie

Hi, I am the Managing Director of SonicIQ Limited in the UK. I have been working in the web development industry since 1999 and have been running SonicIQ since 2001. Currently Ruby On Rails is my preferred development platform. I am experienced in designing with web standards, HTML5, CSS3 and Javascript.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>