2

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 ?

n4n5
  • 66
  • 4
  • @connexo I am not sure about that, because in the [real example](https://svelte.dev/repl/18fd54f036fb4f24b7abfd94d4940583?version=3.4.4), he use `then()`. And [here](https://v8.dev/features/dynamic-import) the documentation said that it return a promise – n4n5 Apr 18 '21 at 21:34
  • 3
    I think that this is because you are running this in the REPL. since this is a website it tries to make a request to https://svelte.dev/ChatBox.svelte when using a variable (which does not exist). I think that it works only with the string because the svelte compiler is fetching this and can therefore treat it as a normal import. Try running it on your machine and see if it works. – Computeshorts Apr 18 '21 at 22:09
  • @pabolo12 I can't compile the [template](https://svelte.dev/repl/18fd54f036fb4f24b7abfd94d4940583?version=3.4.4). I got `Error: UMD and IIFE output formats are not supported for code-splitting builds` when compiling :/ – n4n5 Apr 19 '21 at 06:34
  • @pabolo12 I put `inlineDynamicImports: true,` to my `rollup.config.js` and the [normal template](https://svelte.dev/repl/18fd54f036fb4f24b7abfd94d4940583?version=3.4.4) worked. But when I change the code to **my** [template](https://svelte.dev/repl/5fae51bd3e7c42bdbbd0d643761b18dc?version=3.37.0) : he is also trying to fetch and get a 404. I think it's normal if svelte do that (because I understand that he doesn't really use the `.svelte` but the js in the `bundle.js`) but how can I manage to do that ? – n4n5 Apr 19 '21 at 06:53

1 Answers1

0

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

johannchopin
  • 13,720
  • 10
  • 55
  • 101
  • It works great in CodeSandbox but not in local :/ How can I manage to have the code woring ? [my code in sandBox](https://codesandbox.io/s/suspicious-chatelet-vxi4y?file=/package.json) – n4n5 Apr 19 '21 at 11:08
  • Could you provide a minimal GitHub repo example? – johannchopin Apr 20 '21 at 07:20
  • yes, [here](https://github.com/Its-Just-Nans/test-svelte). I use `Svelte` as a `devDependencies` but in your REPL, you use it as a `dependencies` – n4n5 Apr 20 '21 at 10:52