React hooks duplicate react package

血红的双手。 提交于 2020-01-24 20:19:07

问题


As described here, when using hooks in a react library, you often encounter a react error saying hooks can only be called inside the body of a function component The most likely cause for this error is that your library links to its own react package and you main app also, so you end up using 2 different copies of the react package.

One typical solution to this error is to make sure you main app AND your library use the exact same react package.

The solution I use, is to:

  • cd to myMainApp/node_modules/react
  • yarn link
  • cd to myLib
  • yarn link react

This solution works. My main app and my library now use the same react package.

But what if I have multiple main apps? Let's say I have this project structure:

mainApp1 using lib1-1 and lib1-2

mainApp2 using lib2-1 and lib2-2

Both main apps are independent of each other. So lib1-1 and lib1-2 should link to the react package of mainApp1 and lib2-1 and lib2-2 should both link to the react package of mainApp2

How do I do that? When I try to run yarn link in mainApp2/node_modules/react, yarn tells me that there is already a link for react.

Unfortunately, I cannot use yarn link as react2 or something similar.

Any ideas on how to overcome this?

Note: this problem can be overcome by building your library (where react is a devDependency), committing your changes to git after every tweak and than upgrade the library in your main app. But off course, this is not a solution since during developing, you want to link to you libraries instead of re-importing them from the repo's


回答1:


You can install react and react-dom globally, then link all of your projects to the global instance.

The procedure would be similar to the one you're using already, but creating symlinks to the global locations:

yarn global add react
yarn global add react-dom

Then you can link to them from your individual projects.



来源:https://stackoverflow.com/questions/58481465/react-hooks-duplicate-react-package

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!