Skip to content

Instantly share code, notes, and snippets.

@luveti
Created September 19, 2016 17:12
Show Gist options
  • Save luveti/bc53d0ca0e3e67fe9115b824be558c7f to your computer and use it in GitHub Desktop.
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.
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