Skip to main content

Svelte

The JS/TS SDK can be used directly in Svelte components without the need for any wrappers.

Installation

Please refer to the SDK installation section.

Usage

This is an example of using the LiveCodes JS SDK in a Svelte component:

Component.svelte
<script>
import { onMount } from 'svelte';
import { createPlayground } from 'livecodes';

// Embed Options
const options = {
params: {
html: '<h1>Hello World!</h1>',
css: 'h1 {color: blue;}',
js: 'console.log("Hello, Svelte!")',
console: 'open',
},
};

let container;
let playground;
onMount(() => {
createPlayground(container, options).then((p) => {
playground = p; // now the SDK is available
});
// cleanup when the component is destroyed
return () => playground?.destroy();
});
</script>

<div bind:this="{container}"></div>

Embed options, SDK methods and TypeScript types are available as described in the JS/TS SDK documentations.

Alternatively, the SDK function createPlayground can be used as an action.

Example:

Component.svelte
<script>
import { createPlayground } from 'livecodes';
let options = {
// embed options
};
</script>

<div use:createPlayground="{options}"></div>

However, it is recommended to cleanup when the node is unmounted, like that:

Component.svelte
<script>
import { createPlayground } from 'livecodes';
let options = {
// embed options
};

const livecodes = (node, opts) => {
let playground;
const ready = new Promise(async (res) => {
playground = await createPlayground(node, opts);
res();
});
return { destroy: () => ready.then(() => playground?.destroy()) };
};
</script>

<div use:livecodes="{options}"></div>

Demo

show code
import { createPlayground } from 'livecodes';

const options = {
"params": {
"svelte": "<script>\n import { onMount } from 'svelte';\n import { createPlayground } from 'livecodes';\n\n // Embed Options\n const options = {\n params: {\n html: '<h1>Hello World!</h1>',\n css: 'h1 {color: blue;}',\n js: 'console.log(\"Hello, Svelte!\")',\n console: 'open',\n },\n };\n\n let container;\n let playground;\n onMount(() => {\n createPlayground(container, options).then((p) => {\n playground = p; // now the SDK is available\n });\n // cleanup when the component is destroyed\n return () => playground?.destroy();\n });\n</script>\n\n<div bind:this=\"{container}\"></div>\n"
}
};
createPlayground('#container', options);