Skip to content

Instantly share code, notes, and snippets.

@creationix
Created April 19, 2011 04:27
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save creationix/926811 to your computer and use it in GitHub Desktop.
Save creationix/926811 to your computer and use it in GitHub Desktop.
A super simple module system for browsers. Assumes all source files are concatenated and in browser.
define.defs = {};
define.modules = {};
function define(name, fn) {
define.defs[name] = fn;
}
function require(name) {
if (define.modules.hasOwnProperty(name)) return define.modules[name];
if (define.defs.hasOwnProperty(name)) {
var fn = define.defs[name];
define.defs[name] = function () { throw new Error("Circular Dependency"); };
return define.modules[name] = fn();
}
throw new Error("Module not found: " + name);
}
define('foo', function () {
return 42;
});
define('mymod', function () {
return {
stuff: "goes here",
"and here": require('foo')
};
});
var MyMod = require('mymod');
@creationix
Copy link
Author

I did the testing so that definition order didn't matter, but after using this for a day, I think you're right.

@drewlesueur
Copy link

I really like this idea.
It's even cooler that node.js added define for defining moduels!
nodejs/node-v0.x-archive@9967c36#commitcomment-458564

With this module in the browser, we can use the same require and define for modules both in node.js and in the browser.

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