Skip to content

Instantly share code, notes, and snippets.

@caub
Last active January 1, 2018 22:12
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save caub/458cfe944f8abcf7b1aec608d0a878cc to your computer and use it in GitHub Desktop.
Save caub/458cfe944f8abcf7b1aec608d0a878cc to your computer and use it in GitHub Desktop.
browser shim for window.import()
window.import = function (transformer) {
const ROOT = location.origin;
const REQUIRE_CACHE = new Map();
const RE_EXT = /\.js\w*$/;
function fqn(url, dirname) {
const {href} = new URL(url.startsWith('http') ? url : (url.startsWith('/') ? ROOT : dirname) + url),
last = href.lastIndexOf('/'), dir = href.slice(0, last+1), name = href.slice(last+1),
filename = name ? (RE_EXT.test(name) ? name: name+'.js') : 'index.js';
return {dir, abs: dir+filename};
}
function require(url) {
if (REQUIRE_CACHE.has(url)) {
return Promise.resolve(REQUIRE_CACHE.get(url).exports);
}
const {dir, abs} = fqn(url, this.__dirname);
if (REQUIRE_CACHE.has(abs)) {
return Promise.resolve(REQUIRE_CACHE.get(abs).exports);
}
if (abs.endsWith('.json')) {
return fetch(abs).then(r => r.json()).then(code => {
const MODULE = {exports: code};
REQUIRE_CACHE.set(abs, MODULE);
return MODULE;
});
}
return fetch(abs).then(r => r.text())
.then(code => {
const executableCode = Function('module', 'exports', '__dirname', 'require', code + '\n\n//# sourceURL=' + abs);
const MODULE = {
__dirname: dir,
exports: {}
};
REQUIRE_CACHE.set(abs, MODULE);
executableCode.call(MODULE.exports, MODULE, MODULE.exports, dir, require.bind(MODULE));
return MODULE.exports;
});
}
return Object.assign(require.bind({__dirname: ROOT}), {cache: REQUIRE_CACHE});
}();
// ex: window.import('https://unpkg.com/js-md5').then(md5 => console.log(md5('test')))
{
"name": "window.import",
"version": "1.0.1",
"description": "browser shim for window.import()",
"repository": "https://gist.github.com/caub/458cfe944f8abcf7b1aec608d0a878cc",
"main": "import.js",
"author": "caub",
"license": "ISC",
"homepage": "https://gist.github.com/caub/458cfe944f8abcf7b1aec608d0a878cc"
}

install with npm i window.import or npm i gist:458cfe944f8abcf7b1aec608d0a878cc

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment