Import function with variable name

Viewed 515

Today, I wanted to try Svelte.

In my code, I wanted to import dynamicly a file, so I saw this question : Dynamically loading component using import or fetch and this REPL.

But I tried to change it to do a "real" dynamic import like this : [my REPL with the test]

function loadChatbox() {
        let nameOfFile = './ChatBox.svelte'
        import(nameOfFile).then(res => Chatbox = res.default)
}

I just changed the string in import by a variable string

BUT the code doesn't work anymore :/ (a real request is sent to the server which respond with a 404)

So my question is : Can I do import like that ?

1 Answers

Your code is completely valid but can't work on a REPL because it doesn't mock a local like environment (if you go from a file to another, the URL doesn't change so there is no way to fetch ChatBox.svelte). Codesandbox can and you will see that it works well there:

Edit priceless-margulis-rjnxg

Related