Event-Emitter
Modern toolchains like Vite or bundlers targeting browsers no longer polyfill Node’s EventEmitter. @avensio/event-emitter fills that gap with a small, type-safe implementation that behaves the same in Node.js and the browser.
Install
bash
pnpm add @avensio/event-emitter
# npm install @avensio/event-emitterHighlights
- Typed events: declare an interface where each key maps to a tuple of argument types (
{ data: [{ id: string }] }). The emitter enforces these signatures at compile time. - Drop-in API:
on,off,once,emit, with extras such asclearListenersandlistenerCountfor teardown and diagnostics. - Zero dependencies: tiny footprint, no polyfills, no globals.
- Unified builds: ESM/CJS/IIFE bundles plus
.d.tsdeclarations for framework and library authors.
How it works
ts
import { EventEmitter } from '@avensio/event-emitter'
type GraphEvents = {
ready: [void]
data: [{ nodes: number }]
error: [Error]
}
const emitter = new EventEmitter<GraphEvents>()
emitter.on('data', ({ nodes }) => console.log('nodes', nodes))
emitter.emit('data', { nodes: 42 })Listeners run synchronously in registration order. Exceptions in a listener propagate to the caller of emit, so wrap handlers when you need isolation.
When to use it
- Framework or SDK internals needing type-safe hooks (
ready,updated,error). - Shared libraries that run both in Node.js (SSR, CLIs) and browsers.
- Replacement for the built-in emitter when targeting environments like Cloudflare Workers, Service Workers, or ESM-only bundlers.
Next steps
- Browse the API reference for signatures, overloads, and behavior.
- Check Usage patterns for recipes (bridging DOM events, composing emitters, automating teardown).
- Read Development workflow before contributing.