diff --git a/docs/pages/index.js b/docs/pages/index.js index c1a2cfb..9c28b55 100644 --- a/docs/pages/index.js +++ b/docs/pages/index.js @@ -4,9 +4,9 @@ import { Editor } from 'codice' import { useLiveCode } from 'devjar/react' export default function Page() { - const [activeFile, setActiveFile] = useState('index.js') + const [activeFile, setActiveFile] = useState('index.mjs') const [files, setFiles] = useState({ - 'index.js': + 'index.mjs': `import React from 'react' import useSWR from 'swr' import Name from './mod1' diff --git a/lib/index.mjs b/lib/index.mjs index b2a9e05..118ed12 100644 --- a/lib/index.mjs +++ b/lib/index.mjs @@ -1,4 +1,8 @@ + async function createModule(files, { getModulePath }) { + const supports = globalThis.HTMLScriptElement.supports || (() => false) + const isImportMapSupported = supports('importmap') + let currentImportMap let shim @@ -12,26 +16,26 @@ async function createModule(files, { getModulePath }) { await shim } - function updateImportMap(imports) { + function updateImportMap(imports, onload, onerror) { imports['react'] = getModulePath('react') imports['react-dom'] = getModulePath('react-dom') const script = document.createElement('script') - script.type = 'importmap-shim' - script.innerHTML = JSON.stringify({ imports }) + script.type = 'importmap' + (isImportMapSupported ? '' : '-shim') + script.textContent = JSON.stringify({ imports }) document.body.appendChild(script) + if (onload) script.onload = onload + if (onerror) script.onerror = onerror if (currentImportMap) { currentImportMap.parentNode.removeChild(currentImportMap) } currentImportMap = script } - function createInlinedModule(code) { return `data:text/javascript;utf-8,${encodeURIComponent(code)}` } - await setupImportMap() const imports = Object.fromEntries( Object.entries(files).map(([key, code]) => [ key, @@ -39,8 +43,18 @@ async function createModule(files, { getModulePath }) { ]) ) - updateImportMap(imports) - return self.importShim('index.js') + if (!isImportMapSupported) { + await setupImportMap() + updateImportMap(imports) + return self.importShim('index.mjs') + } + + return new Promise((resolve, reject) => { + updateImportMap(imports, () => { + resolve(import(/* webpackIgnore: true */ 'index.mjs')) + }), + reject + }) } export { createModule } diff --git a/lib/react.mjs b/lib/react.mjs index 5ea1891..e1e8f4e 100644 --- a/lib/react.mjs +++ b/lib/react.mjs @@ -126,7 +126,7 @@ export function useLiveCode({ getModulePath }) { if (files) { const overrideExternals = - new Set(Object.keys(files).filter(name => !isRelative(name) && name !== 'index.js')) + new Set(Object.keys(files).filter(name => !isRelative(name) && name !== 'index.mjs')) // Always share react as externals overrideExternals.add('react')