@muban/muban
Version:
Writing components for server-rendered HTML
55 lines (54 loc) • 2.59 kB
JavaScript
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
import { pascalCase } from 'change-case';
/**
* A wrapper to allow the registration of "lazy" components.
*
* Instead of providing an actual Component to the `components` array within
* `defineComponent`, this wrapper can be used to provide a "lazy" component.
*
* Lazy components are only loaded when the passed `displayName`
* (1st parameter) exists as a `data-component` attribute in the DOM.
*
* When that is the case, the `getComponent` (2nd parameter) is called, which
* should return a `Promise` with the module exports.
*
* Once loaded, it tries to use the export that matches the `PascalCase` version
* of the `displayName` (which is the default convention). If for some reason
* the export doesn't match this convention, or a file exports two components,
* you can provide the `exportName` (3rd parameter) to be used instead.
*
* @param {string} displayName The name of the component declared in the defineComponent() function
* @param {function} getComponent A function that returns an import of the component file
* @param {string} exportName The name of the exported component
* @returns {Object} LazyComponent
*/
export function lazy(displayName, getComponent, exportName = pascalCase(displayName)) {
const fn = () => __awaiter(this, void 0, void 0, function* () {
const exports = yield getComponent();
const factory = exports[exportName];
if (!factory) {
throw new Error(`Error after lazy loading.\nLazy loaded component "${displayName}" doesn't have export "${exportName}".\nDid you mean one of [${Object.keys(exports)}]`);
}
return factory;
});
fn.displayName = displayName;
fn.isLazy = true;
return fn;
}
/**
* @deprecated
*/
export function supportLazy(component) {
return component;
}
export function isLazyComponent(component) {
return 'isLazy' in component && component.isLazy;
}