Render svelte component to html in Svelte 4

157 Views Asked by At

Is it possible to output HTML from a svelte component server-side in Svelte 4? Something like:

<!--MyComponent.svelte -->
<script lang="ts">
  export let text: string;
</script>
<span>{text}</span>
//script.ts
import MyComponent from './MyComponent.svelte';
const htmlString = MyComponent.render({text: 'Foo'});

console.log(htmlString);
//"<span>Foo</span>"

For context, I'm, building a reporting application in Sveltekit that displays interactive reports, and also generates a PDF version of the same content. I'd like to generate a HTML string from my svelte components, and pass that to Puppeteer to generate a PDF. I could create a https://my-app/print-layout endpoint in my app and have puppeteer access that endpoint, but if possible I'd prefer to generate a HTML from my svelte component within a serverside TS script, and pass the string directly to puppeteer.

It looks like this is possible in Svelte v3 using svelte/register and the render method. From the documentation:

A server-side component exposes a render method that can be called with optional props. It returns an object with head, html, and css properties, where head contains the contents of any svelte:head elements encountered.

You can import a Svelte component directly into Node using svelte/register.

require('svelte/register');

const App = require('./App.svelte').default;

const { head, html, css } = App.render({ answer: 42 });

However, the svelte/register API has been removed as of V4:

This API is removed in Svelte 4. require hooks are deprecated and current Node versions understand ESM. Use a bundler like Vite or our full-stack framework SvelteKit instead to create JavaScript modules from Svelte components.

0

There are 0 best solutions below