Skip to content

Instantly share code, notes, and snippets.

@dy
Last active February 19, 2023 14:56
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 dy/dfe659c662279089369986cbc0fa4060 to your computer and use it in GitHub Desktop.
Save dy/dfe659c662279089369986cbc0fa4060 to your computer and use it in GitHub Desktop.
Import maps core polyfill
<script id='import-maps-polyfill'>
const imports = {}
// intercept all subsequent scripts before init
;(new MutationObserver(rx=>rx.forEach(({target:s}) => {
if (s.tagName !== 'SCRIPT' || s.im) return
if (s.getAttribute('type') === 'importmap') {
Object.assign(imports, JSON.parse(s.textContent).imports)
}
else {
s.textContent = s.textContent.replace(
// find any static import
/(from\s+|import\s+)['"]([\w\-]+)['"]/g,
(unmodified, action, selector) => {
// If we can find a mapped path...
const mapped = imports[selector]
return mapped ?
// ..then update the import to use that mapped URL instead.
`${action}/* ${selector} */ '${mapped}'` :
unmodified;
});
s.im=true
}
}))).observe(document, {childList:true,subtree:true})
</script>
<script type="importmap">
{
"imports": {
"a": "/1",
"a/": "/2/",
"a/b": "/3",
"a/b/": "/4/"
}
}
</script>
<script type="module">
import 'a'
console.log('script run')
</script>
const t={};new MutationObserver((e=>e.forEach((({target:e})=>{"SCRIPT"!==e.tagName||e.im||("importmap"===e.getAttribute("type")?Object.assign(t,JSON.parse(e.textContent).imports):(e.textContent=e.textContent.replace(/(from\s+|import\s+)['"]([\w\-]+)['"]/g,((e,r,n)=>{const o=t[n];return o?`${r}/* ${n} */ '${o}'`:e})),e.im=!0))})))).observe(document,{childList:!0,subtree:!0});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment