0

I'd like to insert component dynamically. But, it fails. Could you someone please tell me about it and advice to solve this? REPL is here.

<script>
let Chatbox;
function loadChatbox() {
    // this is available.
    // import('./ChatBox.svelte').then(res => Chatbox = res.default)
    // but, this is not. Why?? and How to make it??
    const name = './ChatBox.svelte';
    import(name).then(res => Chatbox = res.default)
}
</script>
<button on:click="{loadChatbox}">Load chatbox</button>
<svelte:component this="{Chatbox}" />
Vas Mani
  • 1
  • 1

3 Answers3

0

Why are you trying to separate the component path? I believe if you just change your code to this it would work.

import('./ChatBox.svelte').then(res => Chatbox = res.default)

see Dynamically loading component using import or fetch

Ari Shojaei
  • 361
  • 5
  • 12
0

Try adding "await":

<script>
let Chatbox;
async function loadChatbox() { // need to make this an async function too
    // this is available.
    // import('./ChatBox.svelte').then(res => Chatbox = res.default)
    // but, this is not. Why?? and How to make it??
    const name = './ChatBox.svelte';
    (await import(name)).then(res => Chatbox = res.default) // added await
}
</script>
<button on:click="{loadChatbox}">Load chatbox</button>
<svelte:component this="{Chatbox}" />
bob
  • 7,539
  • 2
  • 46
  • 42
0

I found the solution : https://stackoverflow.com/a/36530495/14858601

// index.js
export { default as Template1 } from './Template1';
export { default as Template2 } from './Template2';


// OtherComponent.js
import * as templates from './index.js'
...
// handy to be able to fall back to a default!
return templates[name] || templates.Template1;
Vas Mani
  • 1
  • 1