Skip to content

registerComponent ​

Registers a component in the global registry and mounts it on the matching elements in the DOM. Use it to instantiate components without the parent → child relationship of the config.components configuration.

This function is inspired by the customElements.define() function of Web Components.

💡 Naming components

When using the registerComponent function to load and mount components, the config.name property of the component is used to register and look for components.

Usage ​

js
import { 
registerComponent
,
importWhenVisible
} from '@studiometa/js-toolkit';
import
Component
from './Component.js';
import
Link
from './Link.js';
// Sync
registerComponent
(
Component
);
// Async
registerComponent
(import('./AsyncComponent.js'));
// Lazy
registerComponent
(
importWhenVisible
(() => import('./LazyComponent.js'), 'LazyComponent'),
); // Custom selector
registerComponent
(
Link
, 'a[href^="https"]');

Parameters

  • ctor (typeof Base | Promise<typeof Base | { default: typeof Base }> | (() => Promise<typeof Base | { default: typeof Base }>)): a component class, a promise resolving to a component class or a module namespace (import(...)), or a factory function returning such a promise (() => import(...))
  • nameOrSelector (string): an optional name or selector to use to find components in the DOM instead of the config.name property

Return value

  • instances (Promise<Base[]>): a promise resolving to the created instances of the component

Instances are mounted independently: if an element fails to mount, it is skipped (and logged with console.error in development) instead of rejecting the whole call, so the resolved array contains every instance that mounted successfully.

Examples ​

Basic usage ​

Use the registerComponent function to register a component globally.

js
import { 
Base
,
registerComponent
} from '@studiometa/js-toolkit';
class
Component
extends
Base
{
static
config
= {
name
: 'Component',
}; }
registerComponent
(
Component
);

Async components ​

Register components asynchronously by providing a dynamic import as parameter. The module's default export is used automatically, so you can pass the import(...) promise directly.

js
import { registerComponent } from '@studiometa/js-toolkit';

registerComponent(import('./AsyncComponent.js'));

You can also pass a factory function returning the import, mirroring how lazy child components are declared. The import is triggered immediately.

js
import { registerComponent } from '@studiometa/js-toolkit';

registerComponent(() => import('./AsyncComponent.js'));

Lazy components ​

You can use the lazy import helpers such as importWhenVisible to register lazy components.

js
import { 
registerComponent
,
importWhenVisible
} from '@studiometa/js-toolkit';
registerComponent
(
importWhenVisible
(() => import('./LazyComponent.js'), 'LazyComponent'),
);

MIT Licensed