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 Component
s 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.
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.
TODOListService
which manages items on the to-do list.StorageService
which saves to-do list items to localStorage
.And some HTML markup. Key points to look out for in the proceeding article:
@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.@inject()
on the constructor of the TODOListService
service to inject dependencies without explicitly calling new StorageService()
.@lazyInject()
decorator to inject services to our Preact Component
at runtime.At the end of this article, you will be able to:
#tutorial #typescript #preact