wedi is deprecated. I am working on a new implementation redi.
A lightweight dependency injection (DI) library for TypeScript, along with a binding for React.
wedi is a lightweight toolkit to let you use dependency injection (DI) pattern in TypeScript and especially React with TypeScript.
- Completely opt-in. It's up to you to decide when and where to apply dependency injection pattern.
- Provide a multi-level dependency injection system.
- Support injecting classes, instances, values and factories.
- Support React class component.
- Support React Hooks (functional component).
You can use wedi to:
- Mange state of applications
- Reuse logic
- Deal with cross-platform problems
- Write code that is loosely-coupled, easy to understand and maintain
This guide assumes basic knowledge of TypeScript, React and dependency injection pattern. If you are totally innocent of any idea above, it might not be the best idea to get started with wedi.
Install wedi via npm or yarn:
npm install wedi
# or
yarn add wedi
Add you need to enable decorator in tsconfig.json.
{
"compilerOptions": {
"experimentalDecorators": true
}
}
Declare something that another class or React component could depend on is very simple. It could just be easy as a ES6 class!
class AuthenticationService {
avatar = 'https://img.yourcdn.com/avatar'
}
wedi let you declare other kinds of dependencies such as plain values and factory functions. Read Dependencies for more details.
You could provide a dependency in a React component, and use it in its child components.
function App() {
const collection = useCollection([AuthenticationService])
return <Provider collection={collection}>
<DeeplyWrapped>
<Profile />
</DeeplyWrapper>
</Provider>
}
function Profile() {
const authS = useDependency(AuthenticationService)
return <img src={authS.avatar} />
}
wedi provide some Hooks that helps you use wedi with RxJS smoothly.
function ReRenderOnNewValue() {
const notificationS = useDependency(NotificationService)
const val = useDependencyValue(notificationS.data$)
// re-return when data$ emits a new value
}
Here is a TodoMVC demo built with wedi.
MIT. Copyright Wendell Hu 2019-2020.