npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

plume-ts-di

v1.2.4

Published

Lightweight & simple dependency injection system for TypeScript based on code generation instead of annotation

Downloads

104

Readme

Plume TS DI

Lightweight & simple dependency injection system for TypeScript based on code generation instead of annotation.

The features offered by this library are kept small. Having just a small set of features enables to:

  • Keep this library simple & easy to maintain
  • Force projets to correctly design their code and to fully avoid circular dependencies

Installation

  1. Add compile time dependency in the package.json file: npm install plume-ts-di
  2. Make sure ttypescript is installed or make sure to have a way to run TS transformers
  3. Add the two transformers that add project JS class information about constructors: npm -D install ts-transformer-classname @wessberg/di-compiler
  4. If using ttypescript, declare the transformers in tsconfig.json file:
"plugins": [
   {"transform": "./di-transformer-adapter.ts" },
   {"transform": "ts-transformer-classname" }
]

Note that the di-compiler might be difficult to configure, that's why it can be easier to create a di-transformer-adapter.ts file in the project and use this file in the tsconfig.json declaration:

import { di } from "@wessberg/di-compiler";
import * as ts from 'typescript';

export default function(program: ts.Program) {
  return di({ program });
}
  1. Plume TS DI can now be used

Usage

  1. Write your classes as usual without any annotation :). Make sure all classes have a unique name: the class name is used as a key in the dependency injection system.
  2. Declare a module (you should have one module per module of your application), for example:
export default function installServicesModule(injector: Injector) {
  // bindings, all classes in the DI system must be declared here
  injector.registerSingleton(LocaleService);
  injector.registerSingleton(IdlenessDetector);
  injector.registerSingleton(SessionService);
  injector.registerSingleton(ObservableNotificationEngine);
  injector.registerSingleton(ObservableNotificationEngine, NotificationEngine);
  injector.registerSingleton(Scheduler);
}
  1. Create & use an Injector in your application entry point, generally index.ts:
const injector = new Injector();
installServicesModule(injector);
// you can now get instances of your singletons :
const instance = injector.getInstance(IdlenessDetector);

About interfaces

TS Interfaces are not compiled into JS and it poses problems with DI. Abstract classes must be used instead. Abstract classes can be implemented as interfaces in TS.

Provider pattern

The provider pattern in DI can be used to have logic added in classes creation, or if you want to have instances of external libraries which do not offer Plume TS DI bindings. Here is an exemple of creating NativeService or BrowserService (both implementing Service) depending on the existence of a native JS function:

export default class ServiceProvider implements Provider<Service> {
  private readonly service: Service;
  
  constructor(private nativeService: NativeService, private browserService: BrowserService) {
    if (typeof nativeFunction === 'function') {
      this.service = nativeService;
    } else {
      this.service = browserService;
    }
  }
  
  get(): Service {
    return this.service;
  }
}

This can then be registered in the Injector: injector.registerSingletonProvider(ServiceProvider, Service);

And voilà, it is now possible to get the correct instance of Service anywhere in the application: constructor(private readonly service: Service)

Global Injector instance

Sometimes and especially to integrate with React it is easier to use a global instance of the Injector in React components. To implement this pattern, two functions are provided:

  • configureGlobalInjector(Injector): Configure the global instance of the injector (should be called in index.ts after the global Injector has been fully configured)
  • getGlobalInstance(ClassType): To get an instance of a type in the global Injector

For example in index.ts:

const injector = new Injector();
installServicesModule(injector);
installComponentsModule(injector);
installApiModule(injector);
// to be called after the injector has been configured
configureGlobalInjector(injector);

And in a React component:

export default function Login() {
  const sessionService = getGlobalInstance(SessionService);
  const messageService = getGlobalInstance(MessageService);

  // return ...
}

Integrating with React or Vue

To integrate with React or Vue, data passed from the dependency injection system to the React/Vue components should rely on the Observable pattern:

  • https://rxjs.dev/
  • https://github.com/BeTomorrow/micro-observables

The Observable pattern integrates way better than other alternatives like Redux.

Moreover, it is generally easier to integrate inside UI component using the global Injector instance.

Instances creation

Instances are created as they are needed. If you want to initialize all instances at startup (which is often a good thing to do), you need to call the method initializeSingletonInstances() on the Injector:

const injector = new Injector();
installServicesModule(injector);
// to be called after the injector has been configured
injector.initializeSingletonInstances();

Dependencies

Plume TS DI relies on:

Release process

  1. run npm login
  2. run npm run release <= yarn must not be used