Skip to content

Instantly share code, notes, and snippets.

@aishikaty aishikaty/LICENSE.txt forked from 140bytes/LICENSE.txt
Last active Mar 11, 2017

Embed
What would you like to do?
Module loader in CommonJS style
(
function (
mods, // module storage
vals // module values storage
) {
return function req ( // return a "require" function
name, // module name OR callback to run
def // module definition
) {
return name.call ? // if first argument is callback
name(req) // run it with "require" as first argument
: def ? // if we define a module
(mods[name] = def) // save it to storage
: name in vals // if we have value saved
? vals[name] // return it
: (vals[name] = ( // else save the value
mods[name]( // of the definition called
req, // with "require" as first argument,
def = { // "module" as second argument
exports: {}
}, def.exports // and "exports" as third argument
) || def.exports // or use module.exports if no value returned
))
}
}
)({}, {})
(function(d,c){return function e(a,b){return a.call?a(e):b?d[a]=b:a in c?c[a]:c[a]=d[a](e,b={exports:{}},b.exports)||b.exports}})({},{})
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
Version 2, December 2004
Copyright (C) 2011 YOUR_NAME_HERE <YOUR_URL_HERE>
Everyone is permitted to copy and distribute verbatim or modified
copies of this license document, and changing it is allowed as long
as the name is changed.
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. You just DO WHAT THE FUCK YOU WANT TO.
{
"name": "tinyCommonJSishModuleLoader",
"description": "Module loader in CommonJS style",
"keywords": [
"module",
"loader"
]
}
<script>
var module = (function(d,c){return function e(a,b){return a.call?a(e):b?d[a]=b:a in c?c[a]:c[a]=d[a](e,b={exports:{}},b.exports)||b.exports}})({},{})
var counter = 1
// simple module definition
module('a', function (require) {
return counter++
})
// CommonJS-ish style
module('b', function (require, module, exports) {
module.exports = counter++
})
// entry point
module(function (require) {
console.assert(require('a') === 1)
console.assert(require('b') === 2)
console.assert(require('a') === 1) // values are cached
console.log('Module loaded!')
})
</script>
<script>
// BONUS: loading modules from network
var loadModule = function (name, base, req) {
req = new XMLHttpRequest()
req.open('GET', base + name + '.js', false)
req.send()
module(name, Function('require', 'module', 'exports', req.responseText))
}
var base = '/scripts/'
loadModule('example', base) // loads /scripts/example.js
console.log(module('example'))
</script>
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.