1
votes

I am using sapper to build a site that consists of many sub-pages that each use a different svelte component (with svg visualizations) and I plan to export it as a static site. Right now I am using a [slug].svelte file to get easy routing for the sub-pages.

My problem is that when I export the site, it generates one single huge [slug]....js file that seems to contain all the data for the visualizations of the sub-pages. Is there a way to get smaller/single js files for each sub-page when using [slug].svelte?

It seems I could just make my routes manually by making a folder for each sub-page and that way generate separate js files. Maybe the problem is that I am importing all the components in a single _select.svelte file to select the right svelte component for each sub-page. I was trying to import the components dynamically in hoping that this would generate a different js file for each sub-page, but then the static site generation won't work. I am probably doing something horribly wrong here...

Thanks for any hints!

2

2 Answers

2
votes

Code-split entry points are created in two cases:

  • A .svelte or .js file is being treated as a route (as in [slug].svelte)
  • A dynamic import is used

It sounds like you want the second option:

<script>
  const imports = {
    a: () => import('./A.svelte'),
    b: () => import('./B.svelte'),
    c: () => import('./C.svelte')
  };

  export let component = 'a';
</script>

{#await imports[component]() then module}
  <svelte:component this={module.default}/>
{/await}

Demo here.

Note that you have to spell out all the different import(...) possibilities — you can't do this sort of thing...

<script>
  const imports = {
    a: './A.svelte',
    b: './B.svelte',
    c: './C.svelte'
  };

  export let component = 'a';
  $: promise = import(imports[component]);
</script>

{#await promise then module}
  <svelte:component this={module.default}/>
{/await}

...because the bundler needs to be able to 'see' which files are dynamically imported when the app is built.

0
votes

There are two different techniques, and I do not know which one suites best. A svelte app is usually shipped as a single bundles.js file. That would contain all code that you have imported anywhere on your svelte files and it can be big.

If you want to optimize the load time of your app, you may be looking for code splitting (dynamic imports). Here's a good answer on that: https://stackoverflow.com/a/60026703/105224

Another way is splitting the project into different svelte apps using multiple rollup configurations (simply export an array of configs instead of a single one). Those apps are totally independent and don't share state. But that looks to me like mixing traditional (express-) routes (each routes has its own html) with svelte. I think that's more interesting if you want to enhance existing (static) pages with dynamic behavior.