从任何给定请求的包中排除未使用的 Svelte 组件
Excluding unused Svelte components from any given request's bundle
以下问题特定于 SvelteKit。
我有一个页面可能会根据服务器从请求中确定的内容呈现各种组件的子集。但是由于服务器已经确定 should/should 不显示的内容,我不想在发送给客户端的最终包中包含任何其他组件,因为客户端永远不需要该特定代码请求。
为了说明,在下面的示例代码中,如果没有错误,我不希望 ErrorToast
的代码包含在包中。
<main>
{#if error}
<ErrorToast {message} />
{/if}
{#if hasImages}
<ImageGallery {images} />
{/if}
{#if showUsage}
<UsageChart {data} />
{/if}
</main>
有没有办法用 SvelteKit 做到这一点?
我尝试了动态导入(使用 await import("$lib/path/to/Component.svelte")
),但这导致 仅 客户端呈现而没有 SSR(绝对不行)。我还尝试通过道具将组件从相应的端点传递到页面,但这似乎自动导入为 Server-side component.
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}/>
以下问题特定于 SvelteKit。
我有一个页面可能会根据服务器从请求中确定的内容呈现各种组件的子集。但是由于服务器已经确定 should/should 不显示的内容,我不想在发送给客户端的最终包中包含任何其他组件,因为客户端永远不需要该特定代码请求。
为了说明,在下面的示例代码中,如果没有错误,我不希望 ErrorToast
的代码包含在包中。
<main>
{#if error}
<ErrorToast {message} />
{/if}
{#if hasImages}
<ImageGallery {images} />
{/if}
{#if showUsage}
<UsageChart {data} />
{/if}
</main>
有没有办法用 SvelteKit 做到这一点?
我尝试了动态导入(使用 await import("$lib/path/to/Component.svelte")
),但这导致 仅 客户端呈现而没有 SSR(绝对不行)。我还尝试通过道具将组件从相应的端点传递到页面,但这似乎自动导入为 Server-side component.
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}/>