Vas Mani
Vas Mani

Reputation: 1

Svelte : Importing component dynamically is not working

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}" />

Upvotes: 0

Views: 1068

Answers (3)

Vas Mani
Vas Mani

Reputation: 1

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;

Upvotes: 0

bob
bob

Reputation: 7985

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}" />

Upvotes: 0

Ari Shojaei
Ari Shojaei

Reputation: 360

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

Upvotes: 0

Related Questions