UNPKG

piral-lazy

Version:

Plugin for lazy loading third-party framework components in Piral.

38 lines 1.53 kB
import { lazy, createElement } from 'react'; import { withApi } from 'piral-core'; export function createLazyApi() { return (context) => { return (api) => { const cache = {}; const getDependency = (name) => { const dep = cache[name]; if (!dep) { throw new Error(`The given dependency "${name}" cannot be found. Please add it first using "defineDependency"`); } return dep.result ?? (dep.result = dep.loader()); }; return { defineDependency(name, loader) { cache[name] = { loader, result: undefined, }; }, fromLazy(load, deps = []) { return lazy(() => Promise.all(deps.map(getDependency)).then((values) => { const depMap = deps.reduce((obj, name, index) => { obj[name] = values[index]; return obj; }, {}); return load() .then((comp) => withApi(context, comp, api, 'unknown')) .then((compWithApi) => ({ default: (props) => createElement(compWithApi, { deps: depMap, ...props }), })); })); }, }; }; }; } //# sourceMappingURL=create.js.map