injection-js is a lightweight (5.2KB minified) dependency injection library specifically designed for JavaScript and TypeScript applications outside of the Angular framework. Extracted from Angular's pre-v5 dependency injection system, it retains its feature completeness, speed, reliability, and robust testing. The library is currently at version 2.6.1 and provides a runtime reflection-based DI solution, differentiating itself from Angular's modern compile-time `StaticInjector`. It is ideal for Node.js, Vue, React, or vanilla JS/TS projects that require a sophisticated DI system without the full Angular ecosystem. Key requirements include a Reflect API polyfill (e.g., `reflect-metadata`) and specific `tsconfig.json` flags for TypeScript decorator support.
npm install injection-jsVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates setting up `injection-js` with decorators and the `inject` function, creating an injector, and resolving dependencies. It includes the necessary `reflect-metadata` import and showcases how services depend on each other.
Install `reflect-metadata` (`npm i reflect-metadata`) and add `import 'reflect-metadata';` at the very top of your application's entry file, before any decorated classes are defined. Alternatively, use `@abraham/reflection` or `core-js/es7/reflect`.
Add or ensure the following in your `tsconfig.json`:
```json
{
"compilerOptions": {
"experimentalDecorators": true,
"emitDecoratorMetadata": true
}
}
```Understand that `injection-js` offers a runtime, reflection-based DI. If you need compile-time DI or are building an Angular application, use `@angular/core`'s built-in DI system. This library is for non-Angular applications that still desire Angular-style DI.
For new projects or refactoring, prioritize using TypeScript with decorators (`@Injectable`, `constructor` type hints) or the `inject` function for dependency resolution, along with the required `tsconfig.json` settings and `reflect-metadata` polyfill.
Install `reflect-metadata` (`npm install reflect-metadata`) and add `import 'reflect-metadata';` as the very first line in your application's main entry point file. This ensures the polyfill loads before any decorated classes are defined.
Open your `tsconfig.json` file and add or set `"experimentalDecorators": true` within the `compilerOptions` section. You will likely also need `"emitDecoratorMetadata": true` for `injection-js` to function correctly with decorators.