0
votes

In my Svelte + Rollup project src folder I have two subfolders, components and pages. Let me describe my dream, and hopefully somebody can shed some light on whether it's possible.

  1. The components and pages are exported as their own files (I have that working via rollup-plugin-multi-input).

  2. When a page is hit, it requests all the components it needs.

  3. The component JS files are then cached. All future page calls that need the same components draw from the cache.

Is this reasonable, or would it be better to just export the pages individually and bundle the components into each page, duplicating code?

Another potential idea

Do an App.svelte file that imports all the components, aggregate those into an object, pass that object into the page component as a prop, then do <svelte:component this={components.Input}> for all components inside the page.

App.svelte:

<script>
  import { onMount } from 'svelte';
  import Input from 'Input.svelte';
  import Popup from 'Popup.svelte';
  const components = {Input, Popup};
  let page;
  function getPage(url) {
    /* AJAX call to fetch the page component and set it to the page variable */
  }
  onMount(() => getPage(location.pathname))
</script>

<svelte:component this={page} components>
Page1.svelte:

<script>
  export let components;
</script>

<p>Type your name:</p>
<svelte:component this={components.Input}>

With this method, all the components are included in the bundle even if the user never hits a page that contains some of those.

1
Have you considered using SvelteKit? You can create an endpoint under routes that allowes you to export components and send response so you can use wherever you want. Have a look at this post if that helps you. With this approach, you won't have to cache any components. Just call the endpoint wherever you need it. :) stackoverflow.com/questions/67941692/… - TheUnKnown

1 Answers

0
votes

It appears that you are talking about some sort of elaborate, manual code-splitting.

When you build a Svelte/Sapper project with Rollup, it will bundle and chunk your components, routes, etc, into a series of smaller chunks of JS, which are loaded only when required, saving bandwidth and increasing speed. You don't need the multi-input plugin for this.

Also note that your plan of loading components via AJAX won't work, since Svelte is a compiled language, and won't build and assign things on the fly in a user's browser.

Out of curiosity, what is the bundle size you are struggling with? Svelte already makes some of the tiniest bundles of any frontend framework, so what are you doing to give you size concerns?