📖 Technical reference

Exact signatures, lifecycle, ordering and error semantics of every public API. For guided examples, see the feature pages.

Package and requirements

  • The package ships ES2020 modules with type declarations (lib/*.js + lib/*.d.ts, source maps included), marked sideEffects: false. It is meant to be consumed through a bundler.
  • With webpack, set resolve.alias.COMPONENTS even in sync mode, to your components folder or to false: the fallback async import is part of the bundle and webpack resolves it at build time.
  • No runtime dependencies. Uses crypto.randomUUID(), MutationObserver and dynamic import(): any evergreen browser (Chrome/Edge 92+, Firefox 95+, Safari 15.4+).
  • Async mode works with any bundler through the loadComponent option: the import() lives in your code, so your bundler splits one chunk per component. Without it, the dispatcher falls back to import(`COMPONENTS/${name}`), which only webpack resolves (with a COMPONENTS alias).
import {
  ComponentDispatcher, type ComponentConstructor, type ComponentLoader,
  EventBus, type QueuedEvent,
  SharedState,
  Logger, LogLevel, type LogEntry
} from 'html-scoped-component-importer';

Component lifecycle

  1. Scan. For each root (default document.body), the root itself and its descendants matching the selector are collected; elements that already have data-uuid are skipped, duplicates across roots are removed.
  2. Mark. Every collected element receives data-uuid (crypto.randomUUID()) before construction. An element is therefore processed at most once per dispatcher, even if its constructor throws.
  3. Group. The attribute value is split on , and trimmed: "A, B" binds two components to the same element.
  4. Construct. new Component(element, dispatcher). Instances are stored in APP_COMPONENTS under the element's uuid.
  5. Destroy. With observeDomChanges(), when the element leaves the document every instance on it gets _destroy() (if defined) and the entry is removed.

Ordering

  • Collected elements are processed in reverse document order (later and deeper elements first).
  • Sync: by registry key order, then element order. All constructors run synchronously before the returned promise resolves.
  • Async: one chunk import per component name, started in parallel; each name's elements are constructed as soon as its chunk resolves, so ordering across names depends on the network.

ComponentDispatcher

new ComponentDispatcher(options?: { events?: EventBus; logger?: Logger; loadComponent?: ComponentLoader })

type ComponentLoader = (name: string) => Promise<{ default: ComponentConstructor }>
MemberSignatureBehaviour
importComponents(registry: Record<string, ComponentConstructor>, target?: Element | Element[]) => Promise<void>Sync mode. Binds names present in registry; unknown names are ignored. Switches the dispatcher to sync mode for the observer.
importAsyncComponents(target?: Element | Element[]) => Promise<void>Async mode. Calls loadComponent(name) (default: imports COMPONENTS/<name>) once per name (cached; concurrent requests share one import; a failed import is retried on the next scan). Resolves when every constructor ran.
observeDomChanges() => () => voidStarts a MutationObserver on document.body; returns the disconnect function. See DOM observation.
Selectorset (selector: string)CSS selector used to find components (default [data-component]; empty string resets). The attribute holding the names is the first data-* in the selector.
compAttributeget: stringThat attribute name without data-, e.g. sync-component.
APP_COMPONENTSget: Map<string, object[]>Live instances keyed by data-uuid, one array entry per component on the element. Arrays since 3.0.0.
eventsreadonly EventBusThe bus from the options, or a new one logging under events.
loggerreadonly LoggerThe logger from the options, or a new one scoped dispatcher.
createState<State extends object>(name: string, initialState: State) => SharedState<State>A SharedState logging under state:<name>.
createComponents / createAsyncComponents—Legacy aliases of the two import methods without target.

Run one dispatcher per mode: the observer re-uses the mode (and sync registry) of the last import call on that instance.

Component contract

type ComponentConstructor = new (element: HTMLElement, dispatcher: ComponentDispatcher) => object;

export default class Tooltip {            // async mode: default export of the module loadComponent('Tooltip') returns
  constructor(element: HTMLElement, dispatcher: ComponentDispatcher) {}
  _destroy?(): void {}                     // optional, called once when the element is removed
}
  • The constructor is the only lifecycle hook for setup; it must be synchronous (start async work inside it if needed).
  • Release listeners, intervals and subscriptions in _destroy(); EventBus.on and SharedState.subscribe return the function to call.
  • Moving an element (remove and re-insert in the same task) keeps its instances: _destroy() is not called.

DOM observation

  • Observes childList with subtree: true on document.body.
  • Each observer callback is handled as one batch: all connected added nodes become the roots of a single scan.
  • Removed nodes still connected (moved) are ignored; otherwise the node and its descendants are destroyed.
  • Attribute changes are not observed: changing data-component on an existing element does nothing.

Error handling

  • A constructor that throws, or a chunk that fails to import, never stops other components.
  • Development builds: the element's children are replaced by an overlay (message and stack trace) and the error goes to dispatcher.logger.error.
  • Other builds: console.error only, the DOM is untouched.
  • The element keeps its data-uuid, so it is not retried; insert a new element to try again.
  • Listener and subscriber errors in EventBus and SharedState are caught per listener and logged; the remaining listeners still run.

EventBus

new EventBus(options?: { maximumQueuedPerEvent?: number /* 50 */; logger?: Logger })

on<Payload>(eventName: string, listener: (payload: Payload) => void): () => void
emit<Payload>(eventName: string, payload?: Payload): void
get queuedEvents(): QueuedEvent[]          // copy, oldest first
onQueueChange(listener: (queuedEvents: QueuedEvent[]) => void): () => void

type QueuedEvent = { eventName: string; payload: unknown; queuedAt: number /* Date.now() */ };
  • Delivery is synchronous, in subscription order.
  • emit with at least one listener for that name delivers immediately and queues nothing.
  • emit with no listener appends to the queue. Beyond maximumQueuedPerEvent for that name, the oldest event of that name is dropped (with a warning).
  • on registers the listener, then synchronously replays every queued event of that name to it in order and removes them from the queue. Only that first listener receives them.
  • When every listener of a name unsubscribed, later emits are queued again.
  • onQueueChange fires after each enqueue, drop and delivery with a fresh snapshot.

SharedState

new SharedState<State extends object>(initialState: State, options?: { logger?: Logger })

get(): Readonly<State>
set(update: Partial<State> | ((current: Readonly<State>) => Partial<State>)): void
subscribe(listener: (next: Readonly<State>, previous: Readonly<State>) => void): () => void
  • set shallow-merges into a new object frozen with Object.freeze (shallow: nested arrays and objects are not frozen, replace them instead of mutating).
  • Subscribers run synchronously after every set, even if no value changed; compare next and previous to skip work.
  • subscribe does not call the listener immediately: render once yourself, as in the examples.

Logger

new Logger(options?: { scope?: string /* 'app' */; enabled?: boolean /* development builds only */ })

debug | info | warn | error | celebrate (message: string, details?: unknown): void
withScope(scope: string): Logger            // same enabled flag, shared entry listeners
onEntry(listener: (entry: LogEntry) => void): () => void

type LogEntry = { level: LogLevel; scope: string; message: string; details?: unknown; timestamp: number };
enum LogLevel { Debug = 'debug', Info = 'info', Warn = 'warn', Error = 'error', Celebrate = 'celebrate' }
  • Each level writes to the matching console method (celebrate uses console.log), with a fixed format string: caller text is never interpreted as % directives.
  • When disabled nothing is written and no entry is emitted.
  • The first ComponentDispatcher created on a page celebrates once through its logger; disable that logger to silence it.

Development detection

Development behaviour (error overlay, logger enabled by default) is on only when the bundler replaced process.env.NODE_ENV with "development". If the expression is not replaced, accessing process throws inside a try and the library falls back to production behaviour.

Performance

  • One querySelectorAll per root and one pass over the matches: cost grows with the number of elements, not with elements × component names.
  • Sync construction allocates no promise per element; the observer runs one scan per mutation batch.
  • Reference numbers (headless Chrome, median, yarn bench): 10,000 elements with 100 component types set up in ≈18 ms; 5,000 elements appended one by one under observation in ≈16 ms.