Last active
February 19, 2023 14:56
-
-
Save dy/dfe659c662279089369986cbc0fa4060 to your computer and use it in GitHub Desktop.
Import maps core polyfill
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
<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> |
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
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