Sticky Module Singleton Utility

0.1.1 · active · verified Sun Apr 19

sticky-module is a specialized JavaScript utility designed to guarantee that a given module is instantiated and evaluated only once, even across multiple imports or different bundling contexts within an application. It achieves this by storing and retrieving module instances using a unique, Symbol-based key, effectively creating an application-wide singleton for that module. This mechanism is particularly useful for libraries or components that require strict single-instance behavior to maintain consistent state or prevent redundant setup in complex module graphs, micro-frontends, or scenarios with multiple bundler outputs. The current stable version is 0.1.1. Its release cadence is likely slow, focusing on stability given its niche purpose. A key differentiator is its Symbol-based internal storage, which offers a robust and collision-resistant approach to global module caching compared to string-based keys.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how sticky-module ensures a module is initialized only once, returning the original instance on subsequent calls.

import stickyModule from 'sticky-module';

console.log('--- First attempt to get module ---');
let [{a, b}, known] = stickyModule('@custom/my-singleton', {
  a: Math.random(),
  b: 'initial value'
});

console.log(`Was module known? ${known}`);    // Expected: false
console.log(`Module values: a=${a}, b='${b}'`); // Shows initial random 'a' and 'b'

// Simulate a delay or another part of the application importing it later
setTimeout(() => {
  console.log('\n--- Second attempt to get module (after delay) ---');
  let [{a: a2, b: b2}, known2] = stickyModule('@custom/my-singleton', {
    a: Math.random(), // This value will be ignored as module is already stored
    b: 'new value, ignored' // This value will also be ignored
  });

  console.log(`Was module known? ${known2}`);    // Expected: true
  console.log(`Module values: a=${a2}, b='${b2}'`); // Shows the *same* initial random 'a' and 'b'

  // Verify they are the same instance/values
  console.log(`Are 'a' and 'a2' the same? ${a === a2}`); // Expected: true
  console.log(`Are 'b' and 'b2' the same? ${b === b2}`); // Expected: true
}, 100);

view raw JSON →