@dark-engine/core
Version:
The lightweight and powerful UI rendering engine without dependencies and written in TypeScript (Browser, Node.js, Android, iOS, Windows, Linux, macOS)
42 lines (41 loc) • 1.15 kB
JavaScript
import { detectIsUndefined, detectIsFunction, illegal, throwThis } from '../utils';
import { component } from '../component';
import { useMemo } from '../use-memo';
const factories = new Map();
function lazy(loader, done) {
return component(
props => {
const scope = useMemo(() => ({ isDirty: false }), []);
const factory = factories.get(loader);
if (detectIsUndefined(factory) && !scope.isDirty) {
const make = async () => {
factories.set(loader, await run(loader));
detectIsFunction(done) && done();
};
scope.isDirty = true;
throwThis(make());
}
return factory ? factory(props) : null;
},
{ displayName: 'Lazy' },
);
}
function run(loader) {
return new Promise((resolve, reject) => {
loader()
.then(module => {
check(module);
resolve(module.default);
})
.catch(reject);
});
}
function check(module) {
if (process.env.NODE_ENV !== 'production') {
if (!module.default) {
illegal('The lazy loaded component should be exported as default!');
}
}
}
export { lazy };
//# sourceMappingURL=lazy.js.map