add lazy component loading helper
This commit is contained in:
@@ -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
43
src/lib/lazy.svelte.ts
Normal 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>;
|
||||
Reference in New Issue
Block a user