使用 import 或 fetch 动态加载组件

ssu*_*wal 5 svelte

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

我在 stackoverflow 中找到了一些适用于 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>
Run Code Online (Sandbox Code Playgroud)

Tho*_*lle 10

同样的功能存在于斯维尔特3,但你只需要动态进口组合分配到正规的变量,你使用的this的财产svelte:component

示例 ( 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 />
Run Code Online (Sandbox Code Playgroud)

  • 太好了,这有效。我在 repl 中尝试了它,它可以正常工作,但是在使用 sveltejs/template 在本地执行时汇总构建失败。借助这个,我还能够在运行时加载外部 mjs 以加载组件。这里是相关项目[主项目](https://github.com/ssuwal/svelte-gettting-statrted)、[组件生成器](https://github.com/ssuwal/svelte-component-generator)和[模块服务器](https://github.com/ssuwal/svelte-test-component-server)。我不得不切换到 mjs,因为导入不喜欢从服务器提供的 svelte 或 html。 (4认同)