Skip to content

Instantly share code, notes, and snippets.

@JavaScriptDude
Last active November 10, 2020 21:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JavaScriptDude/0c26bd09199b6381d83516f8599a9e9c to your computer and use it in GitHub Desktop.
Save JavaScriptDude/0c26bd09199b6381d83516f8599a9e9c to your computer and use it in GitHub Desktop.
JS Template for making a Library that can be consumed by any system that Underscore.js supports (Browser, Node etc...)
// JS Library Template
// This is tooled to not clobber any namespace with the exception of temp var $$LIBDEF$$
// Major boilerplate was swiped from underscore.js and modified to make it more universal
// Eg: $$LIBDEF$$ = { ns: '$Q', library: 'q_lib', version: '0.1.0'};
// This will load a library refereced by singleton $Q like: $Q.hiMom()
// Change as required
$$LIBDEF$$ = { ns: '$Q', library: 'q_lib', version: '0.1.0'};
// Boilerplate (BP) start
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define($$LIBDEF$$.library, factory) :
(global = global || self, (function () {
var _ns = $$LIBDEF$$.ns, _lib = $$LIBDEF$$.library
// BP end
// Assert dependencies
if ( typeof $ === 'undefined' || typeof $.isXMLDoc === 'undefined') throw new Error(`jQuery is not loaded. Cannot load ${_lib}.`)
if ( typeof _ === 'undefined' || !$.isFunction(_.reduceRight)) throw new Error(`underscore.js is not loaded. Cannot load ${_lib}.`)
// Block duplicate loads
if (global[_ns]) {console.log("${_lib} already loaded. Blocking reload.");return}
// BP start
var current = global[_ns];
var exports = global[_ns] = factory();
exports.noConflict = function () { global[_ns] = current; return exports; };
}()));
}(this, (function () {
var _ns = $$LIBDEF$$.ns, _lib = $$LIBDEF$$.library, _ver = $$LIBDEF$$.version
// BP end
// Public Functions
function hiMom(){console.log("Hi Mom")}
// Public Objects
var SomeObj = {jsIsAwesome: true}
// Export definition (Public functions, properties, classes ...)
return {
// BP start
NS: _ns
,LIBRARY: _lib
,VERSION: _ver
// BP end
// Public functions
,hiMom: hiMom
// Public objects
,SomeObj: SomeObj
}
// BP start
})));delete this['$$LIBDEF$$']
// End
@JavaScriptDude
Copy link
Author

After figuring out how underscore.js does their namespacing and library loading, I made my own version to use as a basis for all my future JS libraries. I've only tested in Browser at the moment but the un-tested code paths are pretty much underscore.js code verbatim so it should work OOTB.

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