Skip to content

Instantly share code, notes, and snippets.

@thomasdavis
Forked from ryanflorence/universal-module.js
Created September 7, 2011 01:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save thomasdavis/1199466 to your computer and use it in GitHub Desktop.
Save thomasdavis/1199466 to your computer and use it in GitHub Desktop.
Universal JavaScript Module, supports AMD (RequireJS), Node.js, and the browser.
(function (name, definition){
var theModule = definition(),
hasDefine = typeof define === 'function',
hasExports = typeof module !== 'undefined' && module.exports;
if (hasDefine){ // AMD Module
define(theModule);
} else if (hasExports) { // Node.js Module
module.exports = theModule;
} else { // Assign to common namespaces or simply the global object (window)
// something like this to allow for flat-file/global module extensions
var obj = null;
var namespaces = name.split(".");
var scope = (this.jQuery || this.ender || this.$ || this);
for( var i = 0; i<namespaces.length;i++){
var packageName = namespaces[i];
if( obj && i == namespaces.length-1) {
obj[packageName] = theModule;
} else if( typeof scope[packageName] === "undefined" ){
scope[packageName] = {};
}
obj = scope[packageName];
}
}
})('core.plugin', function () {
// define your module here and return the public API
return { author: "addy" };
});
// AMD
require(['path/to/myModule'], function (myModule){
// use myModule here
});
// Node.js
var myModule = require('myModule');
// Common global namespaces
jQuery.myModule
ender.myModule
$.myModule
// window
myModule
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment