Skip to content

Instantly share code, notes, and snippets.

@potch potch/tinyAMD.js
Last active Feb 4, 2017

Embed
What would you like to do?
Proposal shim for a Minimal AMD system
// # tinyAMD: a Minimal AMD shim.
// I define Minimal AMD as the following:
// * Every define() call provides a module id field (no filename magic)
// * No additional network traffic to fetch modules
// * All dependencies must be defined before a module may be required
// ## Uses
// * small-footprint production shim for use with an r.js optimized project
// * If you write modules in Minimal AMD coding style, you can use tinyAMD
// for both development and production.
// ## Why Minimal AMD?
// * Clean consistent conventions
// * Module dependencies are always at the header of the file
// * No js optmization required beyond concatenation and minification
(function() {
var defined = {};
var resolved = {};
function define(id, deps, module) {
defined[id] = [deps, module];
}
function require(id) {
if (!resolved[id]) {
var definition = defined[id];
if (!definition) {
throw 'Attempted to resolve undefined module ' + id;
}
var deps = definition[0];
var module = definition[1];
var rDeps = [];
for (var i=0; i<deps.length; i++) {
rDeps.push(require(deps[i]));
}
resolved[id] = module.apply(window, rDeps);
}
return resolved[id];
}
window.require = require;
window.define = define;
})();
@mindplay-dk

This comment has been minimized.

Copy link

commented Jul 1, 2013

After looking through the sizable requirejs and finding nothing much I actually need (or want) I started looking around to see if anyone else had the same thought... I came across almond but even that looks complicated just to cover the very simple need your little sample here seems to cover.

Have you actually used this? Does it work? How do you use it in practice?

"Tell me more, tell me more..."

@mindplay-dk

This comment has been minimized.

Copy link

commented Jul 1, 2013

PS: Github thinks I posted this "in a few seconds" - in your face, time travel nay-sayers!

@mindplay-dk

This comment has been minimized.

Copy link

commented Jul 2, 2013

Plain require('foo') didn't work for me - the "r.js" optimizer seems to simply ignore dependencies unless the argument is an array.

So to build with "r.js", I had to use require(['foo']) instead, which means I had to add support for that - and since I had to do that, it also made sense to add support for the optional callback, e.g.:

require(['foo','bar'], function(foo, bar) {
    // ...
});

Rewiew the changes in my fork here.

This is now working nicely for me :-)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.