Package and requirements
- The package ships ES2020 modules with type declarations (
lib/*.js+lib/*.d.ts, source maps included), markedsideEffects: false. It is meant to be consumed through a bundler. - With webpack, set
resolve.alias.COMPONENTSeven in sync mode, to your components folder or tofalse: the fallback async import is part of the bundle and webpack resolves it at build time. - No runtime dependencies. Uses
crypto.randomUUID(),MutationObserverand dynamicimport(): any evergreen browser (Chrome/Edge 92+, Firefox 95+, Safari 15.4+). - Async mode works with any bundler through the
loadComponentoption: theimport()lives in your code, so your bundler splits one chunk per component. Without it, the dispatcher falls back toimport(`COMPONENTS/${name}`), which only webpack resolves (with aCOMPONENTSalias).
import {
ComponentDispatcher, type ComponentConstructor, type ComponentLoader,
EventBus, type QueuedEvent,
SharedState,
Logger, LogLevel, type LogEntry
} from 'html-scoped-component-importer';
Component lifecycle
- Scan. For each root (default
document.body), the root itself and its descendants matching the selector are collected; elements that already havedata-uuidare skipped, duplicates across roots are removed. - 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. - Group. The attribute value is split on
,and trimmed:"A, B"binds two components to the same element. - Construct.
new Component(element, dispatcher). Instances are stored inAPP_COMPONENTSunder the element's uuid. - 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 }>
| Member | Signature | Behaviour |
|---|---|---|
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 | () => () => void | Starts a MutationObserver on document.body; returns the disconnect function. See DOM observation. |
Selector | set (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. |
compAttribute | get: string | That attribute name without data-, e.g. sync-component. |
APP_COMPONENTS | get: Map<string, object[]> | Live instances keyed by data-uuid, one array entry per component on the element. Arrays since 3.0.0. |
events | readonly EventBus | The bus from the options, or a new one logging under events. |
logger | readonly Logger | The 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.onandSharedState.subscribereturn 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
childListwithsubtree: trueondocument.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-componenton 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.erroronly, 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
EventBusandSharedStateare 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.
emitwith at least one listener for that name delivers immediately and queues nothing.emitwith no listener appends to the queue. BeyondmaximumQueuedPerEventfor that name, the oldest event of that name is dropped (with a warning).onregisters 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.
onQueueChangefires after each enqueue, drop and delivery with a fresh snapshot.
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
consolemethod (celebrateusesconsole.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
ComponentDispatchercreated 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
querySelectorAllper 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.