6

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?

Jared
  • 562
  • 1
  • 6
  • 22

1 Answers1

17

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>
Rich Harris
  • 28,091
  • 3
  • 84
  • 99
  • What about if dynamic component is specified only as a string? For example 'ChatBox'? – Ryan Jun 18 '19 at 18:38
  • 2
    Bundlers need the 'x' in `import('x')` at build time so that they can create the necessary code-split chunks. The conventional solution is to have a map of loaders, like `{A: () => import('./A.svelte'), B: () => import('./B.svelte'), ...}` – Rich Harris Jun 18 '19 at 23:56
  • 2
    @RichHarris We kinda need something like this to get introspection into the props that a component exposes for documentation (not production). Is there a way to do this? My ideal solution would be a component that wraps another, and then just spits out the child's props nabbed from the slot. Is that a thing, or is that like witchcraft? ;) (For the record: One of the huge problems with building Design Systems in the past, was manually having to edit documentation updates, so we are trying to avoid this, and auto-generate everything we can from the components themselves) Thx in advance! – adc Apr 24 '20 at 21:34