@de-pa/react
@de-pa/react is a fork of React that adds a
constructor-based dependency injection pattern (powered by
injection-js). The public React API
is unchanged — you can use it exactly like react, and opt into DI where you
want it.
It is used together with the matching renderer, @de-pa/react-dom.
Installation
npm i @de-pa/react @de-pa/react-dom injection-js reflect-metadata --save
Dependency injection requires TypeScript with experimentalDecorators and
emitDecoratorMetadata enabled, and reflect-metadata imported once at your
entry point. Ordinary (non-DI) components need none of this and behave exactly
like stock React.
The bundled type definitions are derived from
@types/react@18.3and require TypeScript ≥ 5.1. Do not also install@types/react— this package ships its own types (they would otherwise conflict).
tsconfig.json:
{
"compilerOptions": {
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"jsx": "react"
}
}
Usage
import 'reflect-metadata';
import { Component, IComponent, InjectionProvider } from '@de-pa/react';
import { render } from '@de-pa/react-dom';
class Service {
method() {
return 'hello world';
}
}
@IComponent()
class App extends Component {
constructor(public service: Service) {
super();
}
render() {
return <div>{this.service.method()}</div>;
}
}
render(
<InjectionProvider providers={[Service]}>
<App />
</InjectionProvider>,
document.body,
);
A component can provide its own services
@IComponent({ providers: [...] }) lets a class declare its own providers. Such
a service is created once per class per enclosing <InjectionProvider> (a
scoped singleton), layered on top of the <InjectionProvider>'s services:
@IComponent({ providers: [LocalService] })
class Panel extends Component {
constructor(public local: LocalService) {
super();
}
render() {
return <div>{this.local.value()}</div>;
}
}
Versioning & React base
@de-pa/react uses its own semantic version. The upstream React version it
is built on is reported at runtime as React.version (and listed below).
@de-pa/react and @de-pa/react-dom are always released together at the same
version.
@de-pa/react |
React base (React.version) |
Notes |
|---|---|---|
0.0.7 |
18.3.1 |
rebased onto React 18; per-class injector + @IComponent({ providers }); drop-in require('@de-pa/react') |
0.0.6 |
17.x |
initial line (React 17 base) |
While on 0.x the API is still evolving. A 1.0.0 will be cut once the DI API
is stable.
License
@de-pa/react is MIT licensed.