How to dynamically import components in Svelte?


There are situations when we do not want to import components statically into our project. This could be useful for performance reasons. In this article we will quickly learn howy to dynamically import components in Svelte.

The process is –

First, create the component which you want to import dynamically.

Then, in parent component store it in a local variable using asynchronous import.

Lastly, show it using <svelte:component>.

Code Example

Create the component which is to be imported. Let’s call it Superhero.svelte

<h1>Captain America is the first avenger</h1>
<p>This component will be dynamically loaded</p>

Now we will use this component in App.svelte.

  let SuperheroVar;
  function loadSuperhero() {
    import('./Superhero.svelte').then(res => SuperheroVar = res.default)

<button on:click="{loadSuperhero}">Load Superhero</button>
<svelte:component this="{SuperheroVar}" />

In this component we declared a local variable SuperheroVar and a function loadSuperhero(). When this function is called, it will import Superhero.svelte from same directory. Remember, you will need to change the path according to the location of your component relative to the calling component. This function is asynchronously storing the Superhero.svelte component into SuperheroVar. Then we can display it using <svelte:component>.

    Tweet this to help others

Live Demo

Sign Up for Our Newsletters

Get only the best articles delivered to your mail

You May Also Like