禁用提升时,如何将 React 库从一个 Yarn 工作区导入到另一个 Yarn 工作区?

Ash*_*n M 7 reactjs react-native yarnpkg yarn-workspaces yarnpkg-v2

我正在使用 Yarn v2 (berry) 来管理具有以下结构的 monorepo:

project-root
  /packages
    react-native-app
      (dependencies: my-hooks-lib, react@17.0.1)
    my-hooks-lib
      (dependency: react@17.0.1)
Run Code Online (Sandbox Code Playgroud)

这是我的 .yarnrc.yml:

yarnPath: ".yarn/releases/yarn-berry.cjs"
nodeLinker: "node-modules"
nmHoistingLimits: "workspaces"
Run Code Online (Sandbox Code Playgroud)

自从我使用 React Native 应用程序以来,我已经禁用了提升。但正因为如此,react-native-app并且my-hooks-lib有单独的副本react@17.0.1,即使版本相同。这会导致Invalid Hooks call错误:

Error: 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
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.
Run Code Online (Sandbox Code Playgroud)

这是因为my-hooks-lib即使版本相同,也使用不同的 React 副本。如果我像这样导入 React ,效果很好:

// inside my-hooks-lib
import React from "../react-native-app/node_modules/react";
Run Code Online (Sandbox Code Playgroud)

我将 React 设置为对等依赖 inside my-hooks-lib,但这也没有帮助,因为 Yarn 创建了一个到my-hooks-libinside 的符号链接react-native-app,但它无法解析 React。然后我将 React 作为开发依赖项安装在项目的根目录下,现在我又回到了原来的问题,因为现在my-hooks-lib指的是项目根目录下的 React 副本。

有没有办法在开发过程中解决这个问题?


更新:作为一种解决方法,我将 React 作为 和 的对等依赖项react-native-appmy-hooks-lib并在项目根目录中将 React 添加为开发依赖项。这就是现在的样子:

<project-root>
  (dev-dependency: react@17.0.1)
  /packages
    /react-native-app
      (dependency: my-hooks-lib, peer-dependency: react@17.0.1)
    /my-hooks-lib
      (peer-dependency: react@17.0.1)
Run Code Online (Sandbox Code Playgroud)

尽管我仍然很想听到更好的解决方案!