Skip to content

Instantly share code, notes, and snippets.

@pixelbucket-dev
Forked from dogoku/stencil-helper.js
Last active January 24, 2021 16:31
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 pixelbucket-dev/c5edf2e42aa89442323c62ea4fa83573 to your computer and use it in GitHub Desktop.
Save pixelbucket-dev/c5edf2e42aa89442323c62ea4fa83573 to your computer and use it in GitHub Desktop.
Helper functions that simplify compiling and running stencil source code in the browser – using worker for transpilation
const myWorker = new Worker('https://gist.githack.com/pixelbucket-dev/b5da356d73f3620f2f18c010c8f7cb00/raw/6647655120b87219f1ab3029eef75d105551edb5/stencil-helper-transpile-worker.js'/* , { type: 'module' } */);
// auto inject the h import, to reduce boilerplate required in source
const h = "import { h } from 'https://cdn.skypack.dev/@stencil/core';\n";
function addHToSources(sources) {
return sources.map(source => h + source);
}
export async function compileStencil(sources) {
if (!sources || !sources.length) {
throw new Error('no source code provided to compile');
}
myWorker.postMessage(addHToSources(sources));
try {
return await new Promise((resolve) => {
myWorker.onmessage = function ({ data }) {
resolve(data);
};
});
} catch (error) { }
}
export async function runStencil(sources, doc = document) {
if (!sources || !sources.length) {
throw new Error('no source code provided to compile');
}
// async load the stencil compiler and get the transpile function
const codes = await compileStencil(sources);
// make a script tag of type module and set script tag's content to the transpiled code
codes.forEach(code => {
const s = doc.createElement('script');
s.type = 'module';
s.innerHTML = code;
// append script tag to execute transpiled code
doc.body.appendChild(s);
})
}
export async function parseFromHTML(selector, doc = document) {
let list = [];
if (typeof selector === 'string') {
list = Array.from(doc.querySelectorAll(selector));
} else if (selector.innerHTML) {
list = [selector];
} else if (list.forEach) {
list = selector;
}
runStencil(list.map((el) => el.textContent.trim()), doc);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment