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

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your reply. I edited my code. I need to use a variable to import dynamically.
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}" />

Comments

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.