install with npm i window.import
or npm i gist:458cfe944f8abcf7b1aec608d0a878cc
Last active
January 1, 2018 22:12
-
-
Save caub/458cfe944f8abcf7b1aec608d0a878cc to your computer and use it in GitHub Desktop.
browser shim for window.import()
This file contains hidden or 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
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'))) |
This file contains hidden or 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
{ | |
"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" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment