The following question is specific to SvelteKit.
I have a page that could potentially render a subset of various components based upon what the server determines from the request. But since the server is already going to determine what should/should not be displayed, I don't want to include any of the other components in the final bundle shipped to the client since the client will never need that code for that specific request.
To illustrate, in the example code below, if there is no error, I don't want the code for ErrorToast
included in the bundle.
<main>
{#if error}
<ErrorToast {message} />
{/if}
{#if hasImages}
<ImageGallery {images} />
{/if}
{#if showUsage}
<UsageChart {data} />
{/if}
</main>
Is there any way of doing this with SvelteKit?
I attempted dynamic imports (using await import("$lib/path/to/Component.svelte")
), but that resulted in only client side rendering with no SSR (definitely not ok). I also attempted to pass the component to the page from the corresponding endpoint via props, but that seemed to automatically import as a Server-side component.
From Rich Harris via Twitter:
your bundler can't know that won't be used, because it can't know that
error
won't change at runtime. closest you can get is this sort of thing:
<script context="module">
export async function load() {
const { error, hasImages, showUsage } = get_props_somehow();
if (error) {
return {
props: {
component: (await import('./ErrorToast.svelte')).default,
props: message
}
}
}
if (hasImages) {
// ...
}
if (showUsage) {
// ...
}
}
</script>
<script>
export let component;
export let props;
</script>
<svelte:component this={component} {...props}/>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With