I'm trying to call a svelte component from one SvelteKit App to another so I can render it in caller App's DOM. I've created an endpoint that fetches the component, renders it and sends the response to the caller as shown below:
export async function get({ query, page }) {
const ASSET = (await import("../../assets/myasset.svelte")).default;
if (ASSET) {
let renderedAsset = ASSET.render();
return {
body: { asset: renderedAsset }
};
} else {
return {
status: data.status,
error: new Error(`Could not load ${response}`)
}
}
}
<svelte:head>
<script>
let div = document.querySelector('.my-class');
div.addEventListener('click', function () {
window.alert('IT Works');
});
</script>
</svelte:head>
<h1 class="my-class">HELLO</h1>
<style>
h1 {
color: blue;
}
</style>
I get this object on the caller side:
{
"asset": {
"html": "\n<h1 class=\"my-class s-ZmOKpGJa32Cj\">HELLO</h1>",
"css": {
"code": "h1.s-ZmOKpGJa32Cj{color:blue}.s-ZmOKpGJa32Cj{}",
"map": null
},
"head": "<script class=\"s-ZmOKpGJa32Cj\" data-svelte=\"svelte-muoug1\">let div = document.querySelector('.my-class');\n div.addEventListener('click', function () {\n window.alert('IT Works');\n });\n </script>"
}
}
I'm injecting this in the caller's DOM like this:
{@html `<${''}style>${Final.asset.css.code }</${''}style>` }
{@html Final.asset.html}
{@html Final.asset.head}
<svelte:head>
<script>
import { onMount } from 'svelte';
onMount(() => {
let div = document.querySelector('.my-class');
div.addEventListener('click', function () {
window.alert('IT Works');
});
});
</script>
</svelte:head>
<h1 class="my-class">HELLO </h1>
<style>
h1 {
color: blue;
}
</style>
Uncaught SyntaxError: Cannot use import statement outside a module.
How can I use svelte's functionality(svelte code/in-built functions/ hydration part) and export it to be used by another App?