Skip to content

favyorg/di

Repository files navigation

@favy/di

codecov npm version npm bundle size GitHub

A lightweight and powerful dependency injection library for TypeScript.

Features

  • 🚀 Create modules as easily as functions
  • 🔧 Easily replace any dependency at any level
  • 🌟 Simple integration into any project
  • 💪 Full TypeScript support with type inference
  • 🧩 High extensibility and support for Higher Kinded Types
  • 🎯 Caching and lazy initialization

Why @favy/di?

Unlike many other solutions, @favy/di offers:

  • Minimal syntax: No need for decorators or complex configurations.
  • Easy integration: A module is just a function, so it can be integrated anywhere.
  • Performance: Minimal runtime overhead.
  • Flexibility: Easily adapts to different programming styles and patterns.

Installation

npm install @favy/di

Quick Start

import { Module } from '@favy/di';

const SimpleModule = Module()('SimpleModule', () => 'Hello, DI!');
console.log(SimpleModule()); // Output: Hello, DI!

// Simple module combination
const ModuleA = Module()('ModuleA', () => 10);
const ModuleB = Module()('ModuleB', () => 5);
const CombinedModule = Module()('CombinedModule', ($) => $.ModuleA + $.ModuleB);
console.log(CombinedModule({ ModuleA, ModuleB })); // Output: 15

Advanced Usage

Partial Application with .provide()

const CalculatorModule = Module<{ x: number, y: number }>()('Calculator', ({ x, y }) => x + y);
const PartialCalculator = CalculatorModule.provide({ x: 5 });
console.log(PartialCalculator({ y: 3 })); // Output: 8

Lazy Initialization

const Module = makeModule({
  lazy: false
});

const LazyModule = Module()('LazyModule', () => {
  console.log('LazyModule initialized');
  return 42;
});

const Consumer = Module()('Consumer', ($) => {
  setTimeout(() => $.LazyModule, 1000);
});

Consumer({ LazyModule }); 
// Prints "LazyModule initialized" after 1 second

Cache Management

const Module = makeModule({
  cache: 'module' 
});

const CachedModule = Module()('CachedModule', () => Math.random());
console.log(CachedModule()); // Random number
console.log(CachedModule()); // Same number

Module.flushCache(); // Clear cache
console.log(CachedModule()); // New random number

Documentation

For more detailed information about the library's capabilities and usage examples, please refer to our full documentation.

Contributing

We welcome community contributions! If you have suggestions for improvements or have found a bug, please create an issue or submit a pull request.

License

@favy/di is distributed under the MIT license. See the LICENSE file for more information.