Wrapper of Inversify to inject your dependencies in the components, made with TypeScript and compatible with Vue, React and other component libraries.

Overview

Inversify Props

This package is a wrapper of Inversify to simplify how inject your dependencies with property decorators in the components, made with TypeScript and compatible with Vue, React and other component libraries.

Do you use Hooks? You can try the experimental package inversify-hooks

GitHub last commit GitHub license GitHub forks GitHub contributors GitHub issues

logo

Installation

$ npm install inversify-props reflect-metadata --save

The inversify-props type definitions are included in the inversify-props npm package.

How to use

import 'reflect-metadata'; // Import only once
import { container, inject } from 'inversify-props';

container.addSingleton<IService1>(Service1);
container.addSingleton<IService2>(Service2);

export default class extends Component {
  @inject() service1: IService1;
  @inject() service2: IService2;
}

Alternative usage (without magic)

import 'reflect-metadata'; // Import only once
import { cid, container, inject } from 'inversify-props';

container.addSingleton<IService1>(Service1);

export default class extends Component {
  @inject(cid.IService1) service1: IService1;
}

How to use this library outside of a component

container.addSingleton<IService1>(Service1, 'MyService1');

// You can inject in other services as a Prop
export class MyOtherService {
  @inject() private service1: IService1;
}

// Also in the constructor as a param
export class MyOtherService {
  constructor(@inject() private exampleService: IExampleService) {}
}

// Or in any function as a variable
export function myHelper() {
  const service1 = container.get<IService1>(cid.IService1);
}

You can also use any ID that you prefer

import 'reflect-metadata'; // Import only once
import { container, inject } from 'inversify-props';

container.addSingleton<IService1>(Service1, 'MyService1');

export default class extends Component {
  @inject('MyService1') service1: IService1;
}

⚠️ Important! inversify-props requires TypeScript >= 2.0 and the experimentalDecorators, emitDecoratorMetadata, types and lib compilation options in your tsconfig.json file.

{
    "compilerOptions": {
        "target": "es5",
        "lib": ["es6"],
        "types": ["reflect-metadata"],
        "module": "commonjs",
        "moduleResolution": "node",
        "experimentalDecorators": true,
        "emitDecoratorMetadata": true
    }
}

Why we made this package

The idea is to add a simple wrapper that helps us to inject dependencies in components using property decorators, we have also extend a little inversify adding some methods that make our experience injecting dependencies easier.

You probably don't need this if:

  • You have experience using inversify and you don't need to simplify the process.
  • You want to use all the power of inversify, we are only injecting dependencies like services, helpers, utils...
  • You don't want to inject your dependencies as properties.

How register a dependency

Inversify needs an id to register our dependencies, this wrapper is going to do this for you 'magically' but if you want to uglify the code, keep reading the docs 🤓 .

First of all create a class and an interface with the public methods of your class.

// iservice1.ts
export interface IService1 {
    method1(): string;
}

// service.ts
@injectable()
export class Service1 implements IService1 {
  method1(): string {
    return 'method 1';
  }
}

Note: Don't forget to decorate the class as @injectable() this will made your class candidate to be injectable inside other.

Now is time to register the service in the container, we usually do that in app.container.ts or app.ts.

 container.addSingleton<IService1>(Service1);

How to test

There are some helper functions to test, the recommended way to test is beforeEach test:

  1. Reset the Container
  2. Register again all the dependencies of the container (this is your job)
  3. Mock all the necessary dependencies for the test
beforeEach(() => {
  resetContainer();
  containerBuilder();
  mockSingleton<IHttpService>(cid.IHttpService, HttpServiceMock);
});

Other ways to register a class

As inversify accepts, we have configured three types of registration.

  • Singleton: The dependency will be created only once, one dependency - one object.
  • Transient: The dependency will be created each time is injected, one dependency - one object per injection.
  • Request: Special case of singleton, more info in official docs.

How to use in your components

Once your dependencies are registered in the container, is simple as create a property with the name and the interface.

export default class extends Component {
  @inject() service1: IService1;
}

Note: Part of the magic is that the name of the property has to be the name of the interface, this is how we don't need to add the id.

Some examples

How to configure Uglify or Terser

If you want to use Uglify or Terser to obfuscate the code, you will need to add this options to preserve the names of the classes (we need them to generate the ids magically 😉 ).

new UglifyJSPlugin({
  uglifyOptions: {
    keep_classnames: true,
    keep_fnames: true,
  }
});
new TerserPlugin({
  terserOptions: {
    keep_classnames: true,
    keep_fnames: true,
  }
});

Next steps

  • Investigate if can we remove @injectable
You might also like...
Nuxt 3 starter for Directus with Tailwind CSS and lots of other goodies
Nuxt 3 starter for Directus with Tailwind CSS and lots of other goodies

Nuxt 3 / Directus Starter ⚠️ STILL WORK IN PROGRESS - COULD CHANGE DAILY ⚠️ Opinionated starter template for Nuxt 3 using Directus 9 as a backend. Dev

☀️ Free [Tencent cloud OSS] for map bed, PDF files and other attachment management

Tauri is not finished yet, you can use the Web side map bed, I will release the Tauri version later Live Demo English | 简体中文 Features ☀️ Free [Tencent

Crypto viewer - My first Vue project. Simple application for viewing crypto prices among other things

crypto-viewer Project setup yarn install Compiles and hot-reloads for development yarn serve Compiles and minifies for production yarn build Lints

Localizer for Kirby helps to change every localized string within the panel – other plugins included!
Localizer for Kirby helps to change every localized string within the panel – other plugins included!

Localizer for Kirby – A plugin to override Panel and Plugin translations. Attention This plugin is still in Beta and is likely to change. If you find

Townsquare - An unofficial online tool to run Blood on the Clocktower games through Discord or other digital means
Townsquare - An unofficial online tool to run Blood on the Clocktower games through Discord or other digital means

Blood on the Clocktower Grimoire & Town Square ⚠️ This project is no longer acti

Create and manage invoices in your browser. Serverless Invoices is a free invoicing tool for freelancers and small businesses. Made with Vue.js.

Serverless Invoices by Moku Serverless Invoices is a free invoicing tool for freelancers and small businesses. It is open-source and easily extendable

A single-page web-app made to browse and download your Netlify deploys. Built with Vue.js and Vite, deployed on Netlify.

A single-page web-app made to browse and download your Netlify deploys. Built with Vue.js and Vite, deployed on Netlify.

Organize is a simple GUI application, made using Vue JS and Electron JS, that organizes your files into pre-set folders.
Organize is a simple GUI application, made using Vue JS and Electron JS, that organizes your files into pre-set folders.

Organize is a simple GUI application, made using Vue JS and Electron JS, that organizes your files into pre-set folders.

A vue component or component wrapper that makes an element movable and its movements can be customized.

v-movable A vue component or component wrapper that makes an element movable and its movements can be customized. Live Demo Installation npm i --save

Owner
Nuno Miguel
Nuno Miguel
Alex Vipond 3 Jan 31, 2022
To integrate Rave easily with Javascript Libraries and Frameworks

Rave-Javascript-SDK Implement Rave by Flutterwave easily with Javascript frameworks and Libraries Go to Flutterwave Rave Live to get your LIVE public

Oluwole Adebiyi 3 Mar 14, 2022
You know there are too many JavaScript libraries when there is a game for it 🎯

JavaScript Guessing Game You know there are too many JavaScript libraries when there is a game for it Description React, Flux, Angular, Aurelia, TypeS

Sami Suo-Heikki 409 Aug 17, 2022
Diffusion Bee is the easiest way to run Stable Diffusion locally on your M1 Mac. Comes with a one-click installer. No dependencies or technical knowledge needed.

Diffusion Bee - Stable Diffusion GUI App for MacOS Diffusion Bee is the easiest way to run Stable Diffusion locally on your Intel / M1 Mac. Comes with

Divam Gupta 7.2k Dec 31, 2022
Secure digital asset storage, made in Vue 3, TypeScript and Vite

This repository contains a codebase of OpenVault, a secure digital asset storage application. Contributing Do you want to contribute to this applicati

Ricardo 2 Dec 3, 2021
Fan-made SPA (Single Page Application) website for Evelyn. Created with Vue.js + TypeScript + SASS.

Fan-made SPA (Single Page Application) website for Evelyn. Created with Vue.js + TypeScript + SASS.

Gifaldy Azka 8 Aug 10, 2022
An exemplary real-world application built with Vue.js, Vuex, axios and different other technologies. This is a good example to discover Vue for beginners.

Vue.js codebase containing real world examples (CRUD, auth, advanced patterns, etc) that adheres to the RealWorld spec and API. Project demo is availa

Thinkster 4k Dec 28, 2022
Lend & Borrow - People have a habit of borrowing money from each other frequently, and have trouble remembering who owes whom, and how much.

Lend & Borrow - People have a habit of borrowing money from each other frequently, and have trouble remembering who owes whom, and how much.

techarshgupta 1 Jun 5, 2022
NFT Treasure Chest provide creators with multimedia data (files, pictures, audio, video) on-chain permanent storage and other core functions and services

NFT Treasure Chest NFT Treasure Chest provide creators with multimedia data (files, pictures, audio, video) on-chain permanent storage and other core

Linden 4 Sep 23, 2022
OSL is a simple shared list web-application based on Node. Typical uses include shopping lists of course, and any other small todo-list that needs to be used collaboratively.

Our Shopping List OSL is a simple shared list application. Typical uses include shopping lists of course, and any other small todo-list that needs to

Anaël Ollier 25 Dec 19, 2022