开发外部组件时如何避免“加载两份React"错误? [英] How to avoid `loaded two copies of React` error when developing an external component?

查看:61
本文介绍了开发外部组件时如何避免“加载两份React"错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个外部组件(比方说 my-component,我使用 npm link 链接到项目(因为它正在处理中,我需要包以反映变化).

I am developing an external component (let's say my-component, which I link to the project with npm link (as it is in process and I need the package to reflect changes).

my-component 文件夹中有 node_modules/reactnode_modules/react-dom 因为它们是它的依赖项.但是它们是 peerDependences,所以我不认为将它们带入链接这个包的项目中.

In the my-component folder there are node_modules/react and node_modules/react-dom as they are its dependencies. However they are peerDependences, so I did not suppose to bring them into the project linking this package.

然而,当使用 npm link 时,它会链接整个目录,包括 node_modules.因此,当项目构建时,它包含 2 次包:来自 node_modules/* 和来自 node_modules/my-component/node_modules/*.

However when using npm link, it link the whole directory, including node_modules. So, when the project builds, it includes packages 2 times: from node_modules/* and from node_modules/my-component/node_modules/*.

当组件使用ReactDOM.findDOMNode时,这开始影响,导致这个错误:

This begins to affect when the component is using ReactDOM.findDOMNode, it causes this error:

Warning: React can't find the root component node for data-reactid value `.0.2.0`. If you're seeing this message, it probably means that you've loaded two copies of React on the page. At this time, only a single copy of React can be loaded at a time.

另外,这可能有助于理解发生了什么:只有同时存在 node_modules/my-component/node_modules/reactnode_modules/my-component/node_modules/react 时才会出现问题-dom.如果只有其中之一,则没有错误消息.

Also, it may help to understand what's happening: the problem only appears if there are both node_modules/my-component/node_modules/react and node_modules/my-component/node_modules/react-dom. If there is only one of them, there is no error message.

通常的包安装不会带来这样的错误,因为那里没有node_modules/react-dom.

The usual package installation does not bring such error as there is no node_modules/react-dom there.

如何同时开发外部组件和项目?

How is it supposed to develop an external component and the project at the same time?

推荐答案

问题是双重的:

  1. 您不能加载 2 个 react 副本.
  2. npm 链接创建一个符号链接,但是要求"不尊重符号链接,当它尝试向上导航目录时,它永远不会找到父项目的反应.

解决方案:

您所要做的就是将组件中的 react 和 react-dom 链接到父项目的 node_modules 文件夹中.

All you have to do is link the react and react-dom in your component to that of parent project's node_modules folder.

转到您的组件项目并删除 react 和 react-dom 然后执行

Go to your component project and remove the react and react-dom then do

npm link ../myproject/node_modules/react
npm link ../myproject/node_modules/react-dom

这篇关于开发外部组件时如何避免“加载两份React"错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆