Created
April 8, 2025 06:45
-
-
Save jonrandy/089a9282baed826ee1ae8f3573ca8126 to your computer and use it in GitHub Desktop.
HTML Hash Modules (self contained JS modules in an HTML file)
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
<!doctype html> | |
<html lang="en"> | |
<body> | |
<script type="hash-module" id="sum"> | |
export const sum = (a, b) => a + b; | |
</script> | |
<!-- All hash modules need to go before this script. --> | |
<!-- This cant be a type="module", it must be executed immediately. --> | |
<script> | |
// Ported from https://github.com/tomlarkworthy/lopecode | |
const imports = {} | |
document.querySelectorAll("script[type=hash-module]").forEach(module => { | |
imports["#" + module.id] = URL.createObjectURL(new Blob([module.text], { type: "application/javascript" })) | |
}) | |
const importmap = document.createElement("script") | |
importmap.type = "importmap" | |
importmap.text = JSON.stringify({ imports }, null, 2) | |
document.head.appendChild(importmap) | |
</script> | |
<script type="module"> | |
import { sum } from "#sum" | |
document.body.innerHTML = sum(1, 2) | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment