Skip to content

Instantly share code, notes, and snippets.

@cblanquera
Created August 4, 2020 12:33
Show Gist options
  • Save cblanquera/6c309ddf2a294e5e82d2fd6cd76e3f83 to your computer and use it in GitHub Desktop.
Save cblanquera/6c309ddf2a294e5e82d2fd6cd76e3f83 to your computer and use it in GitHub Desktop.
Example polyfill that implements inline js modules
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
</head>
<body>
<script type="mjs" src="./utils">
let n = 1;
export const log = message => {
const output = document.createElement('pre');
output.textContent = `[${n++}] ${message}`;
document.body.appendChild(output);
};
</script>
<script type="mjs" src="dogs">
import {log} from './utils';
log("Exporting dog names.");
export const names = ["Kayla", "Bentley", "Gilligan"];
</script>
<script type="mjs">
import {log} from './utils';
import {names as dogNames} from 'dogs';
log(`Imported dog names: ${dogNames.join(", ")}.`);
</script>
<script type="module">
// polyfill.js
export {};
for (const original of document.querySelectorAll('script[type=mjs]')) {
const replacement = document.createElement('script');
replacement.setAttribute('type', 'module');
if (original.hasAttribute('src')) {
replacement.setAttribute('cache', original.getAttribute('src'));
}
const transformedSource = original.textContent.replace(
// Find anything that looks like an import or from
/(from\s+|import\s+)['"]([^'"]+)['"]/g,
(unmodified, action, selector) => {
// If we can find a suitable script with that id...
const refEl = document.querySelector(`script[type=module][src][cache="${selector}"]`);
return refEl ?
// ..then update the import to use that script's src URL instead.
`${action}'${refEl.src}'` :
unmodified;
});
// Include the updated code in the src attribute as a blob URL that can be re-imported.
replacement.src = URL.createObjectURL(
new Blob(
[transformedSource],
{ type: 'application/javascript' }
)
);
// Insert the updated code inline, for debugging (it will be ignored).
replacement.textContent = transformedSource;
original.replaceWith(replacement);
}
</script>
</body>
</html>
@cblanquera
Copy link
Author

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