add lazy component loading helper

This commit is contained in:
Elijah Duffy
2025-09-01 17:19:32 -07:00
parent db4f149302
commit 31049fc343
3 changed files with 71 additions and 5 deletions

View File

@@ -50,3 +50,4 @@ export {
getNavigationManager,
type NavigationItemOpts
} from './navigation.svelte';
export { createLazyComponent, type LazyComponentProps } from './lazy.svelte';

43
src/lib/lazy.svelte.ts Normal file
View File

@@ -0,0 +1,43 @@
import type { Component, ComponentProps } from 'svelte';
/**
* Create a lazy-loaded Svelte component.
* Example:
* const LazyComponent = createLazyComponent(() => import('./MyComponent.svelte'));
* @param importFn - Function that returns a promise resolving to the component module.
* @returns An object containing the lazy-loaded component, loading state, error state, and a load function.
*/
export function createLazyComponent<T extends Component>(importFn: () => Promise<{ default: T }>) {
let component = $state<T | null>(null);
let loading = $state(true);
let error = $state<Error | null>(null);
const load = async () => {
try {
const module = await importFn();
component = module.default;
loading = false;
} catch (e) {
error = e as Error;
loading = false;
}
};
return {
get component() {
return component;
},
get loading() {
return loading;
},
get error() {
return error;
},
load
};
}
/**
* Props for a lazy-loaded Svelte component.
*/
export type LazyComponentProps<T extends Component> = ComponentProps<T>;