Skip to content

Instantly share code, notes, and snippets.

@whoisYeshua
Created March 23, 2024 04:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save whoisYeshua/0e9fe5fa336143a50521ae7f150cee33 to your computer and use it in GitHub Desktop.
Save whoisYeshua/0e9fe5fa336143a50521ae7f150cee33 to your computer and use it in GitHub Desktop.
Dynamic importmap content loading from JSON file
{
"imports": {
"react": "https://esm.sh/stable/react@18.2.0/es2022/react.mjs",
"react-dom/client": "https://esm.sh/stable/react-dom@18.2.0/es2022/client.js"
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<script>
const getImportmapData = () => {
const request = new XMLHttpRequest()
request.open('GET', './importmap.json', false) // `false` makes the request synchronous
request.send()
if (request.status === 200) {
return JSON.parse(request.response)
}
return null
}
const importmapData = getImportmapData()
const im = document.createElement('script')
im.type = 'importmap'
im.textContent = JSON.stringify(importmapData)
document.currentScript.after(im)
</script>
<script type="module">
import React from 'react'
import { createRoot } from 'react-dom/client'
const root = createRoot(document.getElementById('app'))
root.render(React.createElement('h1', null, 'Hello from React'))
</script>
</head>
<body>
<div id="app"></div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment