Last active
February 11, 2024 22:32
-
-
Save liammclennan/4639397 to your computer and use it in GitHub Desktop.
DIY modules
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function (root) { | |
// declare a module and its dependencies | |
root.define = function define(name, dependencies, moduleFactory) { | |
root.amdModules = root.amdModules || {}; | |
if (!_.isArray(dependencies) && typeof dependencies !== 'function') | |
throw new Error('dependencies must be an array. moduleFactory must be a function.'); | |
root.amdModules[name] = { | |
'moduleFactory': moduleFactory || dependencies, | |
'dependencies': typeof (moduleFactory) === 'undefined' ? [] : dependencies | |
}; | |
}; | |
// build a module and its dependencies. Modules are cached. | |
root.require = function require(name) { | |
var module = root.amdModules[name], | |
deps = []; | |
if (typeof module === 'undefined') { | |
throw "Module " + name + " could not be found"; | |
} | |
if (module.cached) return module.cached; | |
for (var i = 0; i < module.dependencies.length; i++) { | |
deps.push(require(module.dependencies[i])); | |
} | |
module.cached = module.moduleFactory.apply(this, deps); | |
return module.cached; | |
}; | |
root.requireTest = function requireTest(name, overrides) { | |
var module = root.amdModules[name], | |
deps = []; | |
if (typeof module === 'undefined') { | |
throw "Module " + name + " could not be found"; | |
} | |
for (var i = 0; i < module.dependencies.length; i++) { | |
if (overrides[module.dependencies[i]]) { | |
deps.push(overrides[module.dependencies[i]]); | |
} else { | |
deps.push(require(module.dependencies[i])); | |
} | |
} | |
return module.moduleFactory.apply(this, deps); | |
}; | |
if (typeof exports !== 'undefined') { | |
exports.define = define; | |
exports.require = require; | |
} | |
})(window); |
It is definitely wrong. I have an updated version, which I will post soon.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Is there a typo on line 23? Should the call to requireAmd be a call to req instead?