Skip to content

Instantly share code, notes, and snippets.

@thurt
Last active January 21, 2016 03:10
Show Gist options
  • Save thurt/34087583a3caf1405e9c to your computer and use it in GitHub Desktop.
Save thurt/34087583a3caf1405e9c to your computer and use it in GitHub Desktop.
node/browser capable module check
(function() {
var Validator = (function() {
var Validator = function(options) {
...
};
Validator.prototype.foo = function foo() {
...
};
return Validator;
})();
if (typeof module !== 'undefined' && typeof module.exports !== 'undefined')
module.exports = Validator;
else
window.Validator = Validator;
})();
@thurt
Copy link
Author

thurt commented Dec 27, 2015

If you want to support AMD you can modify the exporting block as follows:

  if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
    module.exports = Validator;
  }
  else {
    if (typeof define === 'function' && define.amd) {
      define([], function() {
        return Validator;
      });
    }
    else {
      window.Validator = Validator;
    }
  }

@thurt
Copy link
Author

thurt commented Jan 21, 2016

Another alternative:

(function (exports) {
  var Cow = function (name) {
    this.name = name || "Anon cow";
  }

  Cow.prototype = {
    greets: function(target) {
         /* ...  */
    }
  };

   exports.Cow = Cow;
})(this);

@thurt
Copy link
Author

thurt commented Jan 21, 2016

Note: This last solution is less verbose than example 1, but it is also less ideal in a Node run-time because this === global--meaning that we are blindly putting all objects in global scope (greater potential for unintended name collision).
In the first example, we are putting the object on module.exports, which will be in a local variable of the calling module.

As for a browser environment, all of these possibilities will blindly be adding to the window (global scope).

@thurt
Copy link
Author

thurt commented Jan 21, 2016

If a project goes beyond a few script tags, then I think the best alternative is to use browserify instead of script tags.

browserify will create a functioning "local module system" within a javascript file which can bundle all the individual scripts. While there is some overhead to add the local module system into the javascript, it is worth it in terms simplifying deployment and reducing the number of HTTP requests (usually means a faster loading web page).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment