Created
September 19, 2016 17:12
-
-
Save luveti/bc53d0ca0e3e67fe9115b824be558c7f to your computer and use it in GitHub Desktop.
A simple require function that: takes an array of urls, fetches the code using the Fetch API, then evals them using a wrapper that exposes module.exports to the code.
This file contains 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 require (urls, cb) { | |
if (!Array.isArray(urls) && typeof urls === 'string') urls = [urls]; | |
var modules = []; | |
var i = 0, next = function () { | |
fetch(urls[i]) | |
.then(function (response) { | |
return response.text(); | |
}) | |
.then(function (code) { | |
try { | |
var module = eval('(function () { var module = { exports: {} }; (function() { ' + code + ' })(); return module.exports; })();'); | |
modules.push(module); | |
if (++i == urls.length) { | |
cb.apply(this, modules); | |
} | |
else { | |
next(); | |
} | |
} | |
catch (e) { | |
console.error(e); | |
} | |
}) | |
.catch(function (ex) { | |
console.error(ex); | |
}); | |
}; | |
next(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment