Skip to content

Instantly share code, notes, and snippets.

@potch
Last active February 11, 2024 22:34
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save potch/4156519 to your computer and use it in GitHub Desktop.
Save potch/4156519 to your computer and use it in GitHub Desktop.
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
Copy link

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
Copy link

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

@mindplay-dk
Copy link

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