Is it possible to dynamically load a Svelte template at runtime?

主宰稳场 提交于 2019-12-20 03:42:55

问题


I have looked at the documentation for [<svelte:component>] (here), but that looks like I would have had to import all of the possible templates at compile time.

Is it possible in Svelte to load any number of arbitrary templates from something like a fetch() call based on a user action? Then inject data into it?

Would it be inefficient to use <slot> for something like this, if I plan on updating it after the initial load?


回答1:


It's technically possible to create a component from the source text — the REPL does it, for example — since the compiler doesn't care if it's running in Node or the browser. But it's definitely not recommended! (It would defeat the object of using Svelte, since the compiler is somewhat large.)

Instead, you can dynamically import the components themselves, if you're using Rollup (with experimentalDynamicImport and experimentalCodeSplitting) or webpack:

<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>


来源:https://stackoverflow.com/questions/50300176/is-it-possible-to-dynamically-load-a-svelte-template-at-runtime

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