Sapper/Svelte possible to conditionally import components?

半腔热情 提交于 2021-02-08 06:09:54

问题


In Sapper I am trying to import a component only if being rendered client side (using onMount). Is there something similar to React Suspense and React.lazy? Or is there another approach?


回答1:


You can certainly do it that way, yes:

<script>
  import { onMount } from 'svelte';
    
  let Thing;
    
  onMount(async () => {
    Thing = (await import('./Thing.svelte')).default;
  });
</script>

<svelte:component this={Thing} answer={42}>
  <p>some slotted content</p>
</svelte:component>

Demo here.

Alternatively, you could wrap that into a component:

<!-- Loader.svelte -->
<script>
  import { onMount } from 'svelte';
    
  let loader;
  let Component;
    
  onMount(async () => {
    Component = (await loader()).default;
  });
    
  export { loader as this };
</script>

<svelte:component this={Component} {...$$restProps}>
  <slot></slot>
</svelte:component>

{#if !Component}
  <slot name="fallback"></slot>
{/if}
<Loader
  this={() => import('./Thing.svelte')}
  answer={42}
>
  <p>some slotted content</p>
  <p slot="fallback">loading...</p>
</Loader>

Demo here. A caveat with this approach is that slots other than default won't be 'forwarded' to the underlying component.



来源:https://stackoverflow.com/questions/63859576/sapper-svelte-possible-to-conditionally-import-components

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!