A light-weight type-safe Dependency Injection library for JavaScript and TypeScript projects
A light-weight TypeScript-first library for dependency injection.
- Stand-alone, no need to install other dependencies
- Intended for both JavaScript and TypeScript projects
- Supports three-shakeable injection tokens
- Inspired by Angular and InversifyJS
- Uses native ECMAScript TC39 decorators (currently stage 3)
- No need for
experimentalDecorators
andemitDecoratorMetadata
- No need for
reflect-metadata
or other reflection libraries
A simple example using constructor injection:
import { injectable, inject } from '@dirkluijk/needle-di';
@injectable()
class FooService {}
@injectable()
class BarService {
constructor(
private fooService = inject(FooService)
) {}
}
By using the @injectable
decorator, there is no need to register your services. Just create a new dependency injection container and request something by its token:
import { Container } from '@dirkluijk/needle-di';
const container = new Container();
const barService = container.get(BarService);
Or just:
import { bootstrap } from '@dirkluijk/needle-di';
const barService = bootstrap(BarService);
Check out the advanced examples below to learn more!
- Constructor injection
- Three-shakable injection tokens
- Auto-binding using decorators
- Supports many kinds of tokens:
- Any class reference
- Any
string
orsymbol
- Any instance of
InjectionToken<T>
(for full type-safety)
- Supports many different providers:
- Class references
- Static values
- Dynamic factories
- Async factories
- Multi providers
- Inheritance support
If you rely on many advanced features, this library could be too limited. In that case, we recommend InversifyJS instead. However, if you prefer a light-weight library that works out of the box and provides full type-safety, please give it a shot!
- Extend the Container API
- Scoping
- ...
Please file an issue if you like to propose new features.
npm install @dirkluijk/needle-di