Code Splitting with Svelte

Okay… this is the situation…

I’m using Svelte + svelte-routing + Meteor and I’d like to split my code to load what user needs in that moment and not all the application bundle.

I came from Angular and thanks to Its routing system, I can easily split my code between different modules.

How can I accomplish the same result using Svelte instead?

1 Like

Here is one way (disclaimer: didn’t check for errors), but in general, all you need to do is use dynamic imports.

  const props = {
     answer: 42

{#await import('./AnotherComponent.svelte')}
{:then { default: comp } }
  <svelte:component this={comp} {props}/>

1 Like

Okay, but what if I’m using a routing system, for example svelte-routing?

I’m not familiar with svelte-routing, but the concept is very much the same:

import new stuff dynamically when you need it.

Also, a search in svelte-routing repo’s issues with keywords “dynamic imports” yielded this:

  import { Router, Link, Route } from "svelte-routing";
  import Loadable from "svelte-loadable";
  import { Home } from "./routes";

  export let url = "";

<Router url="{url}">
    <Link to="/">Home</Link>
    <Link to="test">Test</Link>
    <Route path="test">
      <Loadable loader={() => import("./AsyncComponent.svelte")} />
    <Route path="/"><Home /></Route>

Cool! Thank you, mate! :+1:


Pretty cool man! Thanks for finding this! :slight_smile: I haven’t had need for this yet, but its 100% one I will keep in my back pocket also! I am so glad to see Meteor + Svelte getting more and more traction!

1 Like