使用 import 或 fetch 动态加载组件

Dynamically loading component using import or fetch

有没有办法使用 fetch 或 import 在 svelte 中动态导入组件?可能是从可共享组件创建的 svelte 文件或模块文件(仍然不知道它是如何工作的)。很新很苗条,很兴奋。

我在 Whosebug 中找到了一些适用于 v2 的代码。这是


<button on:click="loadChatbox()">
  chat to a customer service representative
</button>

{#if ChatBox}
  <svelte:component this={ChatBox}/>
{/if}

<script>
  export default {
    methods: {
      async loadChatbox() {
        const { default: Chatbox } = await import('./Chatbox.html');
        this.set({ Chatbox });
      }
    }
  };
</script>

Svelte 3 中存在相同的功能,但您只需将动态导入的组件分配给用于 svelte:component 上的 this 属性 的常规变量。

示例 (REPL)

<!-- App.svelte -->
<script>
  let Chatbox;

  function loadChatbox() {
    import('./ChatBox.svelte').then(res => Chatbox = res.default)
  }
</script>

<button on:click="{loadChatbox}">Load chatbox</button>
<svelte:component this="{Chatbox}" />

<!-- ChatBox.svelte -->
<h1>Dynamically loaded chatbox</h1>
<input />