Skip to content

Instantly share code, notes, and snippets.

@rpominov
Last active August 29, 2015 13:56
Show Gist options
  • Save rpominov/8973106 to your computer and use it in GitHub Desktop.
Save rpominov/8973106 to your computer and use it in GitHub Desktop.
Simple js modules system

This function ("ns") allows you to not care about order of JavaScript files during concatenation. All you need is to wrap code of each file to ns() call, and access other modules via ns() too.

Example:

ns.initAll()

ns('greeting-string', function(exports, module) {
  module.exports = 'Hello world!';
});

ns('app', function(exports, module) {
  var greeting = ns('greeting-string');
  var showPopup = ns('popup').showPopup;
  showPopup(greeting);
});

ns('popup', function(exports, module) {
  exports.showPopup = function(content) {
    alert(content);
  };
});

# You also need to require some entry module
# at the end (when all modules defined) to run initializations chain
ns('app');

# Or you can initialize all modules
ns.initAll();

Disclaimer: it not some RequireJS alternative as it don't dynamically loads modules or something, it just handles initialization order when all javascript is already loaded somehow (for example concatenated to one file)

Blog post (russian): http://pozadi.github.io/2014/02/13/ns.html

window.ns = (function(){
var modules = {};
function _ns(name, initializer) {
if (initializer) {
return modules[name] = function() {
var module = {
exports: {}
};
initializer(module.exports, module);
modules[name] = function() {
return module.exports;
};
return module.exports;
};
} else {
return modules[name]();
}
}
_ns.initAll = function() {
for (var name in modules) {
if (modules.hasOwnProperty(name)) {
modules[name]();
}
}
};
return _ns;
}());
window.ns=function(){function b(b,c){return c?a[b]=function(){
var d={exports:{}};return c(d.exports,d),a[b]=function(){
return d.exports},d.exports}:a[b]()}var a={};return b.initAll=
function(){for(var b in a)a.hasOwnProperty(b)&&a[b]()},b}();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment