Integrate dependency injection to your Preact application. Write readable and less code with services directly injected into your Components and Services.


Preact is a lightweight front-end framework that provides the most useful features from the React framework in a very small, ~3KB, package. One thing that is missing from Preact, or ReactJS, is a mechanism to dependency inject (DI) services.  InversifyJS provides a lightweight and powerful Inversion of Control (IoC) framework that allows us to inject dependencies to our Components and services using decorators. Using InversifyJS on a Preact application, we can reduce the boilerplate code needed for instantiating services.

You can download the completed application at this  GitHub repo.

Screenshot of the application we will be building to understand how to use DI in a JS application


Preferably, the reader should have some experience in TypeScript. Someone with experience in JavaScript and the NodeJS ecosystem can follow this tutorial with some help from Google.

Abstract Lesson

I will create a simple TODO list app as an example to show how to use and benefit from dependency injection. The example app is mainly composed of the following two services and some TypeScript and HTML markup to use them.

  1. TODOListService which manages items on the to-do list.
  2. StorageService which saves to-do list items to localStorage.

And some HTML markup. Key points to look out for in the proceeding article:

  1. How we use the @injectable() decorator in our service classes to let the application know that the class should be added to the list of providers that can be injected.
  2. Use of @inject() on the constructor of the TODOListService service to inject dependencies without explicitly calling new StorageService().
  3. How we build a @lazyInject() decorator to inject services to our Preact Component at runtime.

At the end of this article, you will be able to:

  1. Create a Preact application.
  2. Use InversifyJS to inject services into your components and services.

#tutorial #typescript #preact

Preact With InversifyJS for Dependency Injection
1.60 GEEK