Reputation: 681
How can I render a component that has been compiled using svelte.compile() manually? I'm compiling a component like this:
<script type="module">
import * as svelte from 'svelte/compiler';
var { js: Awesome } = svelte.compile(svelteComponentCode, {
generate: 'dom', //can use 'ssr' too
hydratable: true,
filename: 'Helloworld.svelte'
});
</script>
I have access to Awesome.code
which is the JS compiled from the svelte component and want to use it to render the component to the DOM.
Upvotes: 3
Views: 1663
Reputation: 154
I know this is an old question now, but I think you need to use the same technique that you'll find in the Svelte REPL where you need to create a Blob with the code, and then load and mount that.
const { code } = svelte.compile(inputCode).js;
const blob = new Blob([code], { type: 'text/javascript' });
const url = URL.createObjectURL(blob);
import(url).then(({ default: Component }) => {
new Component({
target: document.body, // or whatever your target is
});
});
The compile is usually done in a webworker to get it off the main UI thread.
There is a nice video on building a barebones REPL that can be used as a nice way to learn about "in browser" svelte compiling; this uses the browser version of rollup as well. That's because your svelte component will probably be importing other code.
https://www.youtube.com/watch?v=S3j1fLzC8_E
There's another really relevant answer here that is far more fleshed out and explains more about linking of imports during the build of a component, although it's more about node build step than an in browser build experience. Regardless, it's likely it can be of some use.
Just remember that the browser doesn't have access to your file system, so imports will need to be loaded from a server when building/bundling an app in the browser.
Upvotes: 3