Dependency Injection for JavaScript & TypeScript

2.6.1 · active · verified Sun Apr 19

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.

Common errors

Warnings

Install

Imports

Quickstart

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.');

view raw JSON →