Code splitting is a fancy name of dynamic imports in ECMAScript (ES).
It is a recommended option when making larger client-side apps that required to perform faster on different devices.
In this article let see an experimental way how we can do code splitting.
The goal is not to download or execute something the user not want to.
Rollup has been supports code splitting in the form of dynamic imports.
It is just a matter of configuring the Rollup so that it chunks all dynamic imports.
The best technique is to split the code at the router level.
Routify is a promising file-based router that has been supporting dynamic imports as an option. So it is good to be used based on our application needs.
Before starting the actual configuration let see some basic things.
Static imports called at the top level and greedily resolved when building.
//Static ES import
import Card from '../components/Card.svelte';
//svelte template can be used as component
<Card/>
Dynamic imports called like a function and return a promise, this will create its own chunk when bundling. This can be called code splitting.
//Dynamically load component on demand (lazy load)
let Card;
import('../components/Card.svelte')
.then(result => Card = result.default);
// this will be used
{#if Card}
<svelte:component this={Card}/>
{/if}
This result Rollup will chunk the file as Card-[hash].js (see docs)
The code can be split into two ways.
1. Router level or page level (Recommended)— This can be multiple components that can be loaded on a single page.
2. Component level or file level (Temporary)— This can load the single component on demand that can be called a lazy load on the user action.
There are some DO NOT things considered as an anti-pattern on different frameworks.
Because we need to understand the goal and real use case of code splitting.
#svelte-3 #javascript #routify #rollup #code-splitting #programming