sveltesveltekitsvelte-3svelte-component

Import Svelte component from a path which is set in string variable


I am trying to import Svelte component from path which is set in string variable.

When I import the component using directly, it is working:

import("./Component.svelte").then(module => {
    Component2 = module.default;
})
.catch(error => {});

But, when I try to define a variable with the path of component and import it, it doesn't:

let filePath = "./Component.svelte"
import(filePath).then(module => {
  Component2 = module.default;
})
.catch(error => {});

Is there anyway that I can import component with variable source path?

Here is the REPL


Solution

  • Using Vite, you can dynamically import components, but there are some restrictions, e.g. if the component is in a subdirectory, you can import using:

    import(`./components/${name}.svelte`)
    

    You cannot have a fully dynamic import because otherwise the build system would not know what files to include in the build (and Svelte files have to be compiled to be usable).

    Edit: Not all of the following limitations may apply to later versions of Vite. E.g. imports without file extension appear to be possible.

    Dynamic import limitations are documented here.

    The rules are in short: