Skip to content
This repository was archived by the owner on Aug 9, 2018. It is now read-only.

Commit 1c798a5

Browse files
Add an example simple AMD loader.
This is useful for dealing with applications that use RequireJS for dependency management. Just the bare minimum necessary to deal with apps that have been through the r.js optimizer so that no async work is needed to initialize stuff.
1 parent 5dca21a commit 1c798a5

File tree

1 file changed

+81
-0
lines changed

1 file changed

+81
-0
lines changed

util/fakerequire.js

+81
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
2+
// This is a brain-dead simple sorta-kinda-AMD-loader.
3+
// Something like this is useful when your AngularJS app is also using RequireJS.
4+
// It doesn't implement the full AMD spec but it implements enough that 'define' should work
5+
// and then you can use loadAmdModule to synchronously execute a particular AMD module.
6+
7+
var amdModules = {};
8+
9+
function define(name, deps, impl) {
10+
11+
if (impl === undefined) {
12+
impl = deps;
13+
deps = [];
14+
}
15+
16+
amdModules[name] = [deps, impl];
17+
18+
}
19+
20+
function require() {
21+
22+
}
23+
require.config = function () {};
24+
25+
function loadAmdModule(name) {
26+
27+
var module = amdModules[name];
28+
29+
if (module) {
30+
if (module[2] === undefined) {
31+
var deps = module[0];
32+
var impl = module[1];
33+
34+
if (! impl) {
35+
throw new Error('AMD module ' + name + ' has no implementation');
36+
}
37+
38+
var args = [];
39+
args.length = deps.length;
40+
for (var i = 0; i < deps.length; i++) {
41+
var depName = deps[i];
42+
43+
if (depName.charAt(0) === '.') {
44+
var baseParts = name.split('/');
45+
baseParts = baseParts.slice(0, baseParts.length - 1);
46+
var depParts = baseParts.concat(depName.split('/'));
47+
for (var j = 0; j < depParts.length; j++) {
48+
var part = name[j];
49+
if (part === '.') {
50+
name.splice(j, 1);
51+
j -= 1;
52+
}
53+
else if (part === '..') {
54+
if (j === 1 && (name[2] === '..' || name[0] === '..')) {
55+
break;
56+
}
57+
else if (j > 0) {
58+
name.splice(j - 1, 2);
59+
j -= 2;
60+
}
61+
}
62+
}
63+
depName = depParts.join('/').replace('./', '');
64+
}
65+
66+
try {
67+
args[i] = loadAmdModule(depName);
68+
}
69+
catch (err) {
70+
// ignore errors while loading dependencies
71+
}
72+
}
73+
module[2] = impl.apply(null, args);
74+
}
75+
return module[2];
76+
}
77+
else {
78+
throw new Error('No AMD module called ' + name);
79+
}
80+
81+
}

0 commit comments

Comments
 (0)