Registry / web-framework / injection-js

injection-js

JSON →
library2.6.1jsnpmunverified

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-js
INSTALL
IMPORT
SIG · INJECTION-JS
I
injection-js
web-frameworkjavascriptv2.6.1
Install
—
Import
—
Disk
—
Pass rate
0/ 6
Env Coverage0 / 6
glibc
18–22
musl
18–22
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18–226 runs
build_error
glibc
node 18–226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

inject
✓ import { inject } from 'injection-js';
✗ const { inject } = require('injection-js');
The `inject` function is a modern way to declare dependencies, typically used within TypeScript classes. While `require` might work in some transpiled environments, the `import` statement is the canonical way for ESM.
ReflectiveInjector
✓ import { ReflectiveInjector } from 'injection-js';
✗ const ReflectiveInjector = require('injection-js').ReflectiveInjector;
`ReflectiveInjector` is the core class for creating and managing dependency injectors. The CJS `require` pattern is common in older Node.js projects or for specific build setups, but ESM `import` is preferred.
Injectable
✓ import { Injectable } from 'injection-js';
✗ import Injectable from 'injection-js/Injectable';
`@Injectable()` is a decorator used to mark classes as providers for the injector. It's a named export, not a default export or a separate file path. Requires `experimentalDecorators` and `emitDecoratorMetadata` in `tsconfig.json`.

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.

import 'reflect-metadata'; // Must be imported once at the application entry point import { inject, ReflectiveInjector, Injectable } from 'injection-js'; @Injectable() class HttpService { public readonly baseUrl = 'https://api.example.com'; constructor() { console.log('HttpService initialized'); } } @Injectable() class LoggerService { log(message: string): void { console.log(`[Log] ${message}`); } } @Injectable() class DataService { private http = inject(HttpService); private logger = inject(LoggerService); constructor() { this.logger.log('DataService created, ready for operations.'); } fetchData(): string { this.logger.log(`Fetching data from: ${this.http.baseUrl}/data`); return `Data from ${this.http.baseUrl} for the current user.`; } } // Create an injector with providers const appInjector = ReflectiveInjector.resolveAndCreate([ HttpService, LoggerService, DataService ]); // Get an instance of DataService from the injector const dataService = appInjector.get(DataService); console.log('Is dataService an instance of DataService?', dataService instanceof DataService); console.log('Fetched:', dataService.fetchData()); // Demonstrate getting another service directly const loggerService = appInjector.get(LoggerService); loggerService.log('Application started successfully.');
Debug
Known issues
gotchaUsing `injection-js` with TypeScript decorators (`@Injectable`) requires a Reflect API polyfill to be present in your environment. Without it, runtime errors will occur when the injector tries to resolve types.
fix
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`.
affects: >=1.0.0
gotchaWhen using TypeScript decorators like `@Injectable()` for dependency injection, you must enable `experimentalDecorators` and `emitDecoratorMetadata` in your `tsconfig.json` compiler options.
fix
Add or ensure the following in your `tsconfig.json`:
```json
{
  "compilerOptions": {
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true
  }
}
```
affects: >=1.0.0
breakingThis library is an extraction of Angular's *pre-v5* dependency injection system (`ReflectiveInjector`). It is fundamentally different from Angular v5+ `StaticInjector`, which uses compile-time DI. Do not expect compatibility with newer Angular DI patterns or the Angular compiler.
fix
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.
affects: >=1.0.0
gotchaWhile `injection-js` supports ES6 and ES5 syntax for defining dependencies, the modern TypeScript-first approach using decorators or the `inject` function is recommended for clarity and type safety. Older patterns using `static get parameters()` or `di.Class` might be harder to maintain.
fix
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.
affects: >=1.0.0
Errors
Common errors & fixes
TypeError: Reflect.getMetadata is not a function
The required Reflect API polyfill (`reflect-metadata` or similar) has not been imported or is not available at runtime when decorated classes are processed.
fix
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.
Experimental support for decorators is a feature that is subject to change in a future release. Set the 'experimentalDecorators' option to remove this warning.
TypeScript compiler is encountering decorator syntax (`@Injectable`) but the `experimentalDecorators` flag is not enabled in `tsconfig.json`.
fix
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.
Upgrade
Version history
2.6.1latest on npm
Audit
Dependencies
reflect-metadatarequiredRequired for the Reflect API polyfill, essential for decorator-based dependency injection in TypeScript and ES5 class syntax.
@abraham/reflectionoptionalAn alternative lightweight Reflect API polyfill, functionally equivalent to `reflect-metadata`.
core-jsoptionalCan provide the Reflect API polyfill via `core-js/es7/reflect` as part of a larger polyfill bundle.
Agent activity
6 hits · last 30 days
node
6
Resources
injection-js — npm install injection-js · libregistry