Security News
pnpm 10.0.0 Blocks Lifecycle Scripts by Default
pnpm 10 blocks lifecycle scripts by default to improve security, addressing supply chain attack risks but sparking debate over compatibility and workflow changes.
injection-js
Advanced tools
injection-js is a lightweight dependency injection library for JavaScript and TypeScript, inspired by Angular's dependency injection system. It allows developers to manage dependencies in a clean and modular way, promoting better code organization and testability.
Basic Dependency Injection
This example demonstrates basic dependency injection using injection-js. The `Car` class depends on the `Engine` class, and the injector resolves and provides the dependencies automatically.
const { ReflectiveInjector } = require('injection-js');
class Engine {
start() {
console.log('Engine started');
}
}
class Car {
constructor(engine) {
this.engine = engine;
}
drive() {
this.engine.start();
console.log('Car is driving');
}
}
const injector = ReflectiveInjector.resolveAndCreate([Engine, Car]);
const car = injector.get(Car);
car.drive();
Injection Tokens
This example shows how to use injection tokens to inject primitive values or non-class dependencies. The `ApiService` class depends on an API URL, which is provided using an injection token.
const { ReflectiveInjector, InjectionToken } = require('injection-js');
const API_URL = new InjectionToken('apiUrl');
class ApiService {
constructor(apiUrl) {
this.apiUrl = apiUrl;
}
getData() {
console.log(`Fetching data from ${this.apiUrl}`);
}
}
const injector = ReflectiveInjector.resolveAndCreate([
{ provide: API_URL, useValue: 'https://api.example.com' },
{ provide: ApiService, useClass: ApiService, deps: [API_URL] }
]);
const apiService = injector.get(ApiService);
apiService.getData();
Hierarchical Injectors
This example demonstrates hierarchical injectors, where a child injector can inherit dependencies from a parent injector. The `Car` class is resolved in the child injector, while the `Engine` class is resolved in the parent injector.
const { ReflectiveInjector } = require('injection-js');
class Engine {
start() {
console.log('Engine started');
}
}
class Car {
constructor(engine) {
this.engine = engine;
}
drive() {
this.engine.start();
console.log('Car is driving');
}
}
const parentInjector = ReflectiveInjector.resolveAndCreate([Engine]);
const childInjector = parentInjector.resolveAndCreateChild([Car]);
const car = childInjector.get(Car);
car.drive();
Inversify is a powerful and flexible inversion of control (IoC) container for JavaScript and TypeScript. It provides a rich set of features for dependency injection, including support for decorators, middleware, and more. Compared to injection-js, Inversify offers a more feature-rich and extensible API, but it may be more complex to set up and use.
tsyringe is a lightweight dependency injection container for TypeScript and JavaScript. It uses decorators and reflection to manage dependencies, making it easy to use and integrate into existing projects. Compared to injection-js, tsyringe is more focused on TypeScript and provides a simpler API for common use cases.
Awilix is a powerful dependency injection container for JavaScript and TypeScript, designed to be easy to use and flexible. It supports various registration methods, including class, function, and value registrations. Compared to injection-js, Awilix offers a more modern and flexible API, with a focus on ease of use and developer experience.
Dependency injection library for JavaScript and TypeScript in 5.2K. It is an extraction of the Angular's dependency injection which means that it's feature complete, fast, reliable and well tested.
Angular version 5 deprecated the ReflectiveInjector
API and introduced StaticInjector
. In short, the dependency injection in the newest versions of Angular will happen entirely compile-time so reflection will not be necessary.
However, if you want to use dependency injection in your Node.js, Vue, React, Vanilla JS, TypeScript, etc. application you won't be able to take advantage of StaticInjector
the way that Angular will because your application won't be compatible with Angular compiler.
This means that if you need dependency injection outside of Angular @angular/core
is not an option. In such case, use injection-js
for fast, small, reliable, high-quality, well designed and well tested solution.
$ npm i injection-js
# OR
$ yarn add injection-js
Note:
For ES5
Class
syntax and TypeScript you need a polyfill for the Reflect API. You can use:Also for TypeScript you will need to enable
experimentalDecorators
andemitDecoratorMetadata
flags within yourtsconfig.json
import 'reflect-metadata';
import { ReflectiveInjector, Injectable, Injector } from 'injection-js';
class Http {}
@Injectable()
class Service {
constructor(private http: Http) {}
}
@Injectable()
class Service2 {
constructor(private injector: Injector) {}
getService(): void {
console.log(this.injector.get(Service) instanceof Service);
}
createChildInjector(): void {
const childInjector = ReflectiveInjector.resolveAndCreate([Service], this.injector);
}
}
const injector = ReflectiveInjector.resolveAndCreate([Service, Http]);
console.log(injector.get(Service) instanceof Service);
const { Inject, ReflectiveInjector } = require('injection-js');
class Http {}
class Service {
static get parameters() {
return [new Inject(Http)];
}
constructor(http) {
this.http = http;
}
}
const injector = ReflectiveInjector.resolveAndCreate([Http, Service]);
console.log(injector.get(Service) instanceof Service);
require('reflect-metadata');
var di = require('injection-js');
var Http = di.Class({
constructor: function() {},
});
var Service = di.Class({
constructor: [
Http,
function(http) {
this.http = http;
},
],
});
var injector = di.ReflectiveInjector.resolveAndCreate([Http, Service]);
console.log(injector.get(Service) instanceof Service);
For full documentation check Angular DI docs:
This is a list of libraries that are using injection-js. If you have a suggestion on what to add, please don't hesitate to submit a PR.
MIT
FAQs
Dependency Injection library for JavaScript and TypeScript
The npm package injection-js receives a total of 306,500 weekly downloads. As such, injection-js popularity was classified as popular.
We found that injection-js demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
pnpm 10 blocks lifecycle scripts by default to improve security, addressing supply chain attack risks but sparking debate over compatibility and workflow changes.
Product
Socket now supports uv.lock files to ensure consistent, secure dependency resolution for Python projects and enhance supply chain security.
Research
Security News
Socket researchers have discovered multiple malicious npm packages targeting Solana private keys, abusing Gmail to exfiltrate the data and drain Solana wallets.