Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

didi

nikku272.6kMIT10.2.2TypeScript support: included

Dependency Injection for JavaScript

di, inversion of control, dependency, injection, injector

readme

didi

CI

A tiny inversion of control container for JavaScript.

About

Using didi you follow the dependency injection / inversion of control pattern, decoupling component declaration from instantiation. Once declared, didi instantiates components as needed, transitively resolves their dependencies, and caches instances for re-use.

Example

import { Injector } from 'didi';

function Car(engine) {
  this.start = function() {
    engine.start();
  };
}

function createPetrolEngine(power) {
  return {
    start: function() {
      console.log('Starting engine with ' + power + 'hp');
    }
  };
}

// define a (didi) module - it declares available
// components by name and specifies how these are provided
const carModule = {

  // asked for 'car', the injector will call new Car(...) to produce it
  'car': ['type', Car],

  // asked for 'engine', the injector will call createPetrolEngine(...) to produce it
  'engine': ['factory', createPetrolEngine],

  // asked for 'power', the injector will give it number 1184
  'power': ['value', 1184] // probably Bugatti Veyron
};

// instantiate an injector with a set of (didi) modules
const injector = new Injector([
  carModule
]);

// use the injector API to retrieve components
injector.get('car').start();

// alternatively invoke a function, injecting the arguments
injector.invoke(function(car) {
  console.log('started', car);
});

// if you work with a TypeScript code base, retrieve
// a typed instance of a component
const car: Car = injector.get<Car>('car');

car.start();

For real-world examples, check out Karma or diagram-js, two libraries that heavily use dependency injection at their core. You can also check out the tests to learn about all supported use cases.

Usage

Learn how to declare, inject and initialize your components.

Declaring Components

By declaring a component as part of a didi module, you make it available to other components.

type(token, Constructor)

Constructor will be called with new operator to produce the instance:

const module = {
  'engine': ['type', DieselEngine]
};

factory(token, factoryFn)

The injector produces the instance by calling factoryFn without any context. It uses the factory's return value:

const module = {
  'engine': ['factory', createDieselEngine]
};

value(token, value)

Register a static value:

const module = {
  'power': ['value', 1184]
};

Injecting Components

The injector looks up dependencies based on explicit annotations, comments, or function argument names.

Argument Names

If no further details are provided the injector parses dependency names from function arguments:

function Car(engine, license) {
  // will inject components bound to 'engine' and 'license'
}

Function Comments

You can use comments to encode names:

function Car(/* engine */ e, /* x._weird */ x) {
  // will inject components bound to 'engine' and 'x._weird'
}

$inject Annotation

You can use a static $inject annotation to declare dependencies in a minification safe manner:

function Car(e, license) {
  // will inject components bound to 'engine' and 'license'
}

Car.$inject = [ 'engine', 'license' ];

Array Notation

You can also the minification save array notation known from AngularJS:

const Car = [ 'engine', 'trunk', function(e, t) {
  // will inject components bound to 'engine' and 'trunk'
}];

Partial Injection

Sometimes it is helpful to inject only a specific property of some object:

function Engine(/* config.engine.power */ power) {
  // will inject 1184 (config.engine.power),
  // assuming there is no direct binding for 'config.engine.power' token
}

const engineModule = {
  'config': ['value', {engine: {power: 1184}, other : {}}]
};

Initializing Components

Modules can use an __init__ hook to declare components that shall eagerly load or functions to be invoked, i.e., trigger side-effects during initialization:

import { Injector } from 'didi';

function HifiComponent(events) {
  events.on('toggleHifi', this.toggle.bind(this));

  this.toggle = function(mode) {
    console.log(`Toggled Hifi ${mode ? 'ON' : 'OFF'}`);
  };
}

const injector = new Injector([
  {
    __init__: [ 'hifiComponent' ],
    hifiComponent: [ 'type', HifiComponent ]
  },
  ...
]);

// initializes all modules as defined
injector.init();

Overriding Components

You can override components by name. That can be beneficial for testing but also for customizing:

import { Injector } from 'didi';

import coreModule from './core';
import HttpBackend from './test/mocks';

const injector = new Injector([
  coreModule,
  {
    // overrides already declared `httpBackend`
    httpBackend: [ 'type', HttpBackend ]
  }
]);

Type-safety

didi ships type declarations that allow you to use it in a type safe manner.

Explicit Typing

Pass a type attribute to Injector#get to retrieve a service as a known type:

const hifiComponent = injector.get<HifiComponent>('hifiComponent');

// typed as <HifiComponent>
hifiComponent.toggle();

Implicit Typing

Configure the Injector through a service map and automatically cast services to known types:

type ServiceMap = {
  'hifiComponent': HifiComponent
};

const injector = new Injector<ServiceMap>(...);

const hifiComponent = injector.get('hifiComponent');
// typed as <HifiComponent>

Credits

This library builds on top of the (now unmaintained) node-di library. didi is a maintained fork that adds support for ES6, the minification safe array notation, and other features.

Differences to node-di

  • supports array notation
  • supports ES2015
  • bundles type definitions
  • module initialization + module dependencies

License

MIT

changelog

Changelog

All notable changes to didi are documented here. We use semantic versioning for releases.

Unreleased

_Note: Yet to be released changes appear here._

10.2.2

Reverts v10.2.1.

  • FIX: restore main entry (#36)

10.2.1

  • FIX: remove broken main entry

10.2.0

  • FEAT: add ability provide wellknown services (#33)

10.1.0

  • FEAT: add exports field
  • CHORE: internal typing improvements

10.0.1

  • FIX: relax Injector#get type definitions

10.0.0

  • FEAT: turn into module
  • CHORE: require Node >= 16
  • DOCS: significantly improve typescript documentation

9.0.2

  • FIX: correct Injector#instantiate type definitions

9.0.1

  • FIX: correct Injector#invoke type definitions (#20)

9.0.0

Migrates the code base to ES2018.

  • FIX: do not alter input in annotate
  • CHORE: migrate codebase to ES2018
  • CHORE: drop UMD prebuilt distribution

8.0.2

  • FIX: correct dependency detection for annonymous classes (#17)

8.0.1

  • CHORE: simplify initialization logic
  • FIX: drop usage of AggregateError due to poor inspection support

8.0.0

  • FEAT: separate bootstrapping and initialization

Breaking Changes

  • Injector must be manually initialized via Injector#init()

7.0.1

  • FIX: make core ES5, again

7.0.0

  • FEAT: add support for module dependencies and intialization (#13)
  • FEAT: retain stack traces when throwing errors (999b821b)
  • FIX: parse single arg lambda shorthand (d53f6310)
  • CHORE: remove Module from public API
  • CHORE: drop Node@10 support

Breaking Changes

  • Removed Module export. Use documented ModuleDeclaration to define a didi module
  • Improved ModuleDeclaration typings to clearly reflect API used
  • __init__ and __depends__ are now part of the built-in module exports accounted for (#13)

6.1.0

  • FEAT: move to pre-built type definitions

6.0.0

  • FEAT: add type definitions

5.2.1

  • FIX: detect arguments in (async) closures, too

5.2.0

  • CHORE: expose parseAnnotations

5.1.0

  • DOCS: improve

5.0.1

  • FIX: remove async injector from main bundle, will be released seperately

5.0.0

  • FEAT: add async injector :tada:
  • CHORE: no-babel build
  • CHORE: minify using terser

4.0.0

Breaking Changes

  • FIX: remove browser field again; it confuses modern module bundlers. This partially reverts v3.1.0

3.2.0

  • CHORE: mark library as side-effect free via sideEffects: false

3.1.0

  • CHORE: add browser field

3.0.0

Breaking Changes

  • CHORE: don't expose lib folder; library consumers should use API exposed via bundled artifacts

Other Improvements

  • FEAT: allow local overrides on Injector#invoke
  • CHORE: babelify all produced bundles

2.0.1

  • FIX: make injection work on constructor less ES2015 class

2.0.0

  • FEAT: support ES2015 class as injection targets, too
  • FEAT: always instantiate type using new
  • CHORE: bundle es, cjs and umd distributions via rollup

1.0.1 - 1.0.3

  • FIX: properly include resources in bundle

1.0.0

  • FEAT: port to ES2015

...

Check git log for earlier history.