Last active
February 11, 2024 22:40
-
-
Save mflorida/2b807c3ad797027377ed5e75b00fbcd6 to your computer and use it in GitHub Desktop.
Templates for UMD patterns
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* UMD pattern with anonymous function expression | |
*/ | |
(function(){ | |
var umd = function(factory){ | |
if (typeof exports === 'object') { | |
return module.exports = factory(); | |
} | |
else if (typeof define === 'function' && define.amd) { | |
return define([], factory); | |
} | |
else { | |
return this.yourModule = factory(); | |
} | |
}; | |
umd(function(){ | |
return { | |
foo: function(){}, | |
bar: 'bar' | |
}; | |
}); | |
}).call(this); | |
/** | |
* UMD pattern with separate function expression | |
*/ | |
(function(global){ | |
// define module name at top for clarity | |
var module_name = 'yourModule'; | |
// factory function will be exported at the end | |
var factory = function(){ | |
return { | |
foo: function foo(){}, | |
bar: 'bar' | |
} | |
}; | |
if (typeof exports === 'object') { | |
return module.exports = factory(); | |
} | |
else if (typeof define === 'function' && define.amd) { | |
return define([], factory); | |
} | |
else { | |
return global[module_name] = factory(); | |
} | |
})(this); | |
/** | |
* UMD pattern with namespaced object | |
* and separate function expression | |
*/ | |
(function(global){ | |
// define module name at top for clarity | |
var module_name = 'yourModule'; | |
// factory function will be exported at the end | |
var factory = function(){ | |
// name this object for clarity | |
var yourModule = {}; | |
function privateFn(text){ | |
return text | |
} | |
// use named function expressions internally | |
yourModule.doSomething = function doSomething(){}; | |
return yourModule; | |
}; | |
// export to module *AND* AMD *AND* global js | |
if (typeof exports === 'object') { | |
return module.exports = factory(); | |
} | |
if (typeof define === 'function' && define.amd) { | |
return define([], factory); | |
} | |
global[module_name] = factory(); | |
})(this); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment