DEV Community

Discussion on: Dependency Injection in React with Jpex

Collapse
 
itswillt profile image
Will T. • Edited

Nice library! I used to use React Context for dependency injection, but its only limited to React components and React hooks.

However, it might be a little bit harder to do code splitting & lazy loading when we do dependency injection like this because there must be a "parent" that knows of all dependencies.

Another downside is according to the jpex's Documentation, you will also need a Babel/Webpack/Rollup plugin. This way you have coupled your application to the build tool. Now let's say you want to use Vite, you can't unless you write another Vite plugin.

And also, it would be much nicer if we could inject the dependencies without using encase. That way we can write the hooks/services just the way they are supposed to be written. In the backend world, there's awilix that helps to achieve that.

Collapse
 
jackmellis profile image
Jack

I forgot to mention there actually is a jpex plugin for Vite now 🎉
npmjs.com/package/@jpex-js/vite-pl...

Collapse
 
jackmellis profile image
Jack

Thanks for the feedback!

Funnily enough I am using it in a Vite application right now, it took a little bit of fiddling but wasn't too difficult (and will be made into a plugin soon).

As the library is coupled with typescript there must be some build tool involved to turn it into javascript. The real problem I have is a severe lack of reflection tools for both javascript and typescript. It was what forced me down the babel path in the first place!

Saying that, you can use it with no build tools at all, you just lose the "magic" type inference powers.

encase is only one way to skin an ICat 😄 there's also a useResolve hook that lets you write more "traditional" hooks:

const useSomething = () => {
  const someFn = useResolve<SomeFn>();
  // ...
}
Enter fullscreen mode Exit fullscreen mode

I definitely should've made that clear in this post.