The smallest PubSub library possible. Zero Dependencies. 149 bytes. I wrote this article a while back. But I realized...why not just publish the code? Smaller than the competition. Built with JS13K games in mind. Such as cred which is unfortunately in need of some weight loss soon, it is almost 25KB now. If you have any ideas that may trim off even one single byte please share it. Create an issue! I don't mind. The Source This is the entire source (index.js). let t = new EventTarget ( ) ; sub = ( e , c ) => ( t . addEventListener ( e , c ) , ( ) => t . removeEventListener ( e , c ) ) ; pub = ( n , d ) => t . dispatchEvent ( new CustomEvent ( n , { detail : d } ) ) ; Usage npm install pico-pubsub import "pico-pubsub" const unsub = sub ( 'jump' , function ( anything ) { console . log ( "someone jumped - " + anything . detail ) } ) ; pub ( 'jump' , "a_user_id" ) >> "someone jumped - a_user_id" unsub ( ) pub ( 'jump' , "another_user_id" ) >> Nothing happens now Troubleshoot Might add TS support in the future. For now you can use the following snippet. declare global { function pub ( event : string , data : any ) : VoidFunction ; function sub ( event : string , callback : ( data : CustomEvent ) => void ) : void ; } If you have export issues just copy paste and change export type. Prove it The following command will produce a 149b file: npx esbuild index.js --bundle --minify --format=esm --outfile=bundle.js The Competition Coming in at #2 we have nano-pubsub which slims down to an impressive 194b ...Not bad at all! Only ~ 30% larger. /** * @public */ export interface Subscriber < Event > { ( event : Event ) : void ; } /** * @public */ export interface PubSub < Message > { publish : ( message : Message ) => void ; subscribe : ( subscriber : Subscriber < Message > ) => ( ) => void ; } /** * @public */ export default function createPubSub < Message = void > ( ) : PubSub < Message > { const subscribers : { [ id : string ] : Subscriber < Message > } = Object . create ( null ) ...
First seen: 2025-04-01 08:45
Last seen: 2025-04-01 19:47