How to code-split Svelte 5 components

Svelte doesn’t have a built-in way to code-split components. But the new syntax brings it closer to React, so we can borrow the same pattern.


I like to have two components in this setup:

  • MyComponent.svelte – the main component that we want to split into its own bundle
  • index.svelte – the component that shows a loading spinner & renders MyComponent once it’s loaded

There may be other ways to do this but I prefer the Typescript syntax. You can adjust to suit your purposes:

import { onMount, type Component as ComponentType } from 'svelte';
let props = $props();
let Component = $state<ComponentType | null>(null);
onMount(() => {
  // import() triggers the code split, and loads async.
  // webpackChunkName tells Webpack what to name the file (where applicable)
  import('./MyComponent.svelte' /* webpackChunkName: "my-component" */).then(module => {
    Component = module.default as ComponentType;
  });
});

From there we can check in the Svelte template for Component, and render it if it exists:

{#if Component}
  <Component {...props} />
{:else}
  <p>Loading...</p>
{/if}

Leave a Reply

Your email address will not be published. Required fields are marked *