Sveltejs SSR - Property 'render' does not exist on type 'typeof SvelteComponentDev'

Viewed 845

Im trying to server side rendering a svelte component with typescript and rollup.

// renderer.ts
import type { SvelteComponentDev } from 'svelte/internal';
import App from '../../../routes/index.svelte';

export default (): SvelteComponentDev => {
    const { html } = App.render();
    return html;
};

It returns the following errors

Plugin typescript: @rollup/plugin-typescript TS2339: Property 'render' does not exist on type 'typeof SvelteComponentDev'.

From my research, I came up with the following workaround but I'm not a big fan of it. Do you guys have a better way to ssr svelte component in typescript? Thks

// renderer.ts
import type { SvelteComponentDev } from 'svelte/internal';

let App;
import('../../../routes/index.svelte').then(module => {
    App = module.default;
});

export default (): SvelteComponentDev => {
    const { html } = App.render();
    return html;
};
1 Answers

The type definitions are written for the DOM API, not the SSR API, so this is only a matter of type errors which you can silence one way or the other. Possibly the simplest is a type cast to any:

// renderer.ts
import type { SvelteComponentDev } from 'svelte/internal';
import App from '../../../routes/index.svelte';

export default (): SvelteComponentDev => {
    const { html } = (App as any).render();
    return html;
};

By the way you types are wrong here, html is a string, so it should be

// renderer.ts
import type { SvelteComponentDev } from 'svelte/internal';
import App from '../../../routes/index.svelte';

export default (): string => {
    const { html } = (App as any).render();
    return html;
};
Related