微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

我正在使用 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)

这是我的 .yarnrc.yml:

yarnPath: ".yarn/releases/yarn-Berry.cjs"
nodeLinker: "node-modules"
nmHoistingLimits: "workspaces"

自从我使用 React Native 应用程序以来,我已经禁用了提升。但正因如此,react-native-appmy-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.

这是因为 my-hooks-lib 使用不同的 React 副本,即使版本相同。如果我像这样导入 React,它工作正常:

// inside my-hooks-lib
import React from "../react-native-app/node_modules/react";

我在 my-hooks-lib 内使 React 成为对等依赖,但这也无济于事,因为 Yarn 在 my-hooks-lib 内创建了指向 react-native-app 的符号链接,但它无法解决反应。然后我将 React 作为开发依赖项安装在我的项目根目录下,现在我又回到了我原来的问题,因为现在 my-hooks-lib 指的是项目根目录下的 React 副本。

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


更新:作为一种解决方法,我将 React 作为 react-native-appmy-hooks-lib 的对等依赖项,并在项目根。所以这就是它现在的样子:

<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)

尽管我仍然希望听到更好的解决方案!

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。