Skip to content

Instantly share code, notes, and snippets.

@aishikaty
Forked from 140bytes/LICENSE.txt
Last active March 11, 2017 13:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aishikaty/5395f46c938be59ea6fcfa3ecff31620 to your computer and use it in GitHub Desktop.
Save aishikaty/5395f46c938be59ea6fcfa3ecff31620 to your computer and use it in GitHub Desktop.
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