ES6 modules in the browser

This commit is contained in:
Tony Garnock-Jones 2023-12-01 15:02:35 +01:00
parent 5ffc647997
commit c6eef34736
1 changed files with 10 additions and 3 deletions

View File

@ -8,17 +8,21 @@ const __SYNDICATE__ = Syndicate;
const syndicateScripts =
Array.from(document.getElementsByTagName('script'))
.filter(s => s.type === 'text/javascript+syndicate');
.filter(s => (s.type === 'text/javascript+syndicate' ||
s.type === 'syndicate' ||
s.type === 'module+syndicate'));
for (const script of syndicateScripts) {
const isModule = script.type === 'module+syndicate';
const sourceUrl = script.src || script.getAttribute('data-src') || false;
const sourceCode = sourceUrl ? await (await fetch(sourceUrl)).text() : script.innerHTML;
const compilationResult = SyndicateCompiler.compile({
name: sourceUrl || 'anonymous-script-tag',
source: sourceCode,
module: 'none',
runtime: 'Syndicate',
module: isModule ? 'es6' : 'none',
runtime: isModule ? void 0 : 'Syndicate',
emitError: console.error,
});
@ -28,8 +32,11 @@ const __SYNDICATE__ = Syndicate;
Syndicate.Bytes.from(JSON.stringify(sourceMap)).toBase64();
const finalOutput = compilationResult.text + formattedSourceMap;
// console.log(finalOutput);
const replacement = document.createElement('script');
replacement.text = finalOutput;
if (isModule) replacement.type = 'module';
script.parentNode.replaceChild(replacement, script);
}
}