@michaelganchas/ts-inject
v1.0.3
Published
A lightweight TypeScript dependency injection library
Maintainers
Readme
ts-inject
A lightweight, type-safe dependency injection library for TypeScript.
ts-inject simplifies dependency management in TypeScript applications by providing a straightforward and efficient way to inject dependencies, enhancing modularity and testability.
✨ Features
- Type-Safe: Leverages TypeScript's type system for compile-time safety.
- Lightweight: Minimal overhead with a focus on simplicity.
- Flexible: Supports various injection patterns to suit different needs.
- Test-Friendly: Facilitates easy mocking and testing of dependencies.
📦 Installation
npm install @michaelganchas/ts-inject
# or
yarn add @michaelganchas/ts-inject📌 Where to Use
You can use ts-inject in any TypeScript-based project where clean architecture, testability, and modularity matter. Some common use cases include:
- Modular backend applications (e.g. Node.js with Express or Koa)
- Domain-driven design (DDD) implementations
- Microservices and serverless functions
- CLIs and tooling built with TypeScript
- Unit testing with easily mockable dependencies
- Frontend apps (e.g. React, React Native or Vue with TypeScript) that follow service-based architecture
If you're tired of manually wiring dependencies or passing instances all over your codebase,
ts-injectoffers a clean, intuitive alternative.
🔍 Examples
Using the container to register and obtain dependencies:
- First we define our implementation
[src/services/events/eventsService.ts] const send = () => {...} export const eventsService = { send, }; export type EventsService = typeof eventsService;- Then, we set up a key for that implementation
[src/services/events/types.ts] export const EventsServiceKey: PropertyKey = 'EVENTS_SERVICE';- We hook everything up together
[src/services/events/index.ts] container.register<EventsService>(EventsServiceKey, () => eventsService);- Then we're just missing two things:
- A place to import/load all the registrations
[src/core/di/diSetup.ts] import '/src/services/events/index'; ...- And lastly, to run it in our App's entry point as one of the first imports
[src/index.ts] import 'src/core/di/diSetup'; ...
Auto wire dependencies automatically:
- Check the
examples/folder for how to use for either Class injections, or functional ones.
- Check the
📚 API Reference
Check the types.ts file under src/ as it contains all the explanations inside their definitions.
