gpt4 book ai didi

reactjs - 在模块中使用 FormattedMessage 时出错 : Error: [React Intl] Could not find required `intl` object

转载 作者:行者123 更新时间:2023-12-03 14:37:46 27 4
gpt4 key购买 nike

我有一个 monorepo,它公开了一个 TypeScript 模块,该模块由 React TypeScript 项目使用和使用。
当模块将任意 React 元素插入到虚拟 DOM 中时 - 一切都按预期工作,包括当我尝试使用 React Router 时(最初是有问题的,但我能够修复它)。
但是,当我尝试使用 react-intl 时,通过 FormattedMessage ,我得到错误:

Error: [React Intl] Could not find required `intl` object. <IntlProvider> needs to exist in the component ancestry.
当我在控制台日志中看到此打印时,这尤其令人讨厌:
The above error occurred in the <Context.Consumer> component:
in FormattedMessage
in h2
in div
in Loading (at App.tsx:11)
in IntlProvider (at App.tsx:8)
in App (at src/index.tsx:9)
in StrictMode (at src/index.tsx:8)
(注意 IntlProvider 包装 Loading - 这是使用无法找到 FormattedMessageIntlProvider 的元素)。
我想这与版本控制有关,或者有 2 个 React/React DOM/IntlProvider 实例,但我不知道如何解决这个问题,我花了很多时间尝试我能想到的一切。
对于它的值(value),这就是我使用的:
  • TypeScript - 适用于模块和项目
  • Webpack 打包模块,我将 React、ReactDOM 和 react-intl 声明为 externals并将它们添加为 peerDependencies而不是直接依赖
  • create-react-app项目

  • 我能够创建一个最小的重现存储库,这是重现我的问题的方法:
    <cd somewhere>
    git clone https://github.com/chakaz/repro-repo .
    cd repro-lib
    npm install
    npm run build:dev
    cd ../project
    npm install
    npm run start
    有人有什么想法吗?提前致谢!

    最佳答案

    使用上述方法以使其正常工作,您必须删除 node_modules在您的 repro-lib dir 因为它将在两个目录中安装依赖项。
    所以为了解决monorepo的问题, 建议你使用yarn的工作区功能,如下所述:https://classic.yarnpkg.com/en/docs/workspaces/
    总而言之,仅通过 yarn install 即可帮助处理多个工作区是一项很棒的功能。一次。
    以下是使您的 repo 工作的几个步骤:

  • package.json在项目的根级别具有以下内容:
  • {
    "private": true,
    "workspaces": ["project", "repro-lib"]
    }
  • 转至 project dir 并替换 package.json 中的以下行:
  • "pf-common": "file:../repro-lib"
    "pf-common": "1.0.0" 
  • 最后,再次回到 root 顶层 install deps:
  • yarn install
    就是这样!现在您可以重新运行您的应用程序以查看它是如何工作的。
    注意:就对 monorepo 感兴趣而言, lerna它也是通过提供出色的 CLI 来提供帮助的出色工具。

    关于reactjs - 在模块中使用 FormattedMessage 时出错 : Error: [React Intl] Could not find required `intl` object,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63224176/

    27 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com