Link 链接库和工作区应用程序之间的反应版本

Link react versions between linked library and workspace application

我正在为常用组件开发一个 React 库。在我的根文件夹中有:

当我想在工作区中使用 myLib 时,我会像这样导入它:import { Button } from 'myLib'.

在这里,一切似乎都还好。但是在一个组件中我使用了一个钩子并且我有这个错误:

Uncaught Invariant Violation: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app

好像有两个React,npm ls react returns:

└─┬ myLib@1.0.0 invalid
  └── react@16.8.6  extraneous

我试图在 myLib/workspace/ 之间 link 反应和反应-dom node_modules 但是它从来没有用过,这个错误仍然存​​在。


TLDR;

这是我的文件树:

myLib
│   package.json
│   rollup.config.js
│
└───dist/
│
└───src/
│   │   **
│
└───workspace
│   │   package.json
│   │   index.js

到 link myLib 到工作区:我去 myLib/ 然后我做 yarn link 然后我去 workspace/ 我做 yarn link myLib

react 和 react-dom 是 myLib 中的 peerDependenciesworkspace/ 中的 devDependencies


哦当然我已经看过这里了:

我在这里找到了适合我的答案:

我花了一些时间解决这个问题,但答案很简单。如果您有多个版本的 React,则必须转到您的工作区并 link 到 myLib 中的 React 版本。

这个问题的解决方案实际上在react doc:

中有解释

This problem can also come up when you use npm link or an equivalent. In that case, your bundler might “see” two Reacts — one in application folder and one in your library folder. Assuming myapp and mylib are sibling folders, one possible fix is to run npm link ../myapp/node_modules/react from mylib. This should make the library use the application’s React copy.

另一个解决方案是使用 lerna (with hoisting).

这是一个适用于 and 的简单解决方案:

cd /your-library/node_modules/react
yarn link
cd /your-library/node_modules/react-dom
yarn link
cd /your-app
yarn link react
yarn link react-dom

确保 your-library 具有与 your-app 兼容的 React 版本。

或者,如果您使用 ,只需配置别名:

alias: {
  react: path.resolve(__dirname, './node_modules/react'),
  'react-dom': path.resolve(__dirname, './node_modules/react-dom'),
},