Needle is a lightweight & powerful dependency injection container for supporting the development of universal code with full semantic runtime injection. It helps you increase the testability of your applications as well as decoupling your code more effectively
npm install @morgan-stanley/needle reflect-metadataRequires TypeScript >= 5.7 < 6 with experimentalDecorators and emitDecoratorMetadata enabled (see Getting started if you would rather use explicit metadata).
import 'reflect-metadata'; // must be the first import in your app
import { getRootInjector, Injectable } from '@morgan-stanley/needle';
@Injectable()
class Engine {}
@Injectable()
class Car {
constructor(public engine: Engine) {}
}
const car = getRootInjector().get(Car); // Engine is constructed and injected for you- Simple & lightweight
- Can be used in many different JavaScript contexts: node, browsers, angular, react or vanilla js
- Provides a non-invasive way to stand up a tree of dependencies
- Increases your code testability
- Supports semantic versioning injection
Needle works with both TypeScript's legacy experimentalDecorators and standard decorators (TypeScript 5+). With standard decorators there is no constructor metadata, so describe the constructor with deps, or inject into accessor fields:
import { Injectable, Inject, dep, createToken, get } from '@morgan-stanley/needle';
const Config = createToken<{ url: string }>('config');
@Injectable({ deps: [Engine, Config, dep.optional(Logger)] })
class Car {
constructor(engine: Engine, config: { url: string }, logger?: Logger) {}
}
@Injectable()
class Boat {
@Inject(Engine) accessor engine!: Engine;
}See the standard decorators guide for TypeScript settings and migrating from experimentalDecorators.
Full guides live in docs/:
- Getting started, Standard (TC39) decorators, Tokens, Strategies, Factories, Lazy and optional
- Instances and values, External resolution, Caching, Scopes, Interception
- Metrics, Configuration, Errors and logging, Semantic injection, Angular
- Feature support matrix, Module formats (ESM/CJS), Troubleshooting, Contributing and benchmarks
Runnable examples are in examples/ (npm run examples).
See CONTRIBUTING.md and docs/contributing.md for the toolchain and benchmark report.