Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
214 views
in Technique[技术] by (71.8m points)

reactjs - How to avoid `loaded two copies of React` error when developing an external component?

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

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.

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/*.

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.

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.

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?

question from:https://stackoverflow.com/questions/33157904/how-to-avoid-loaded-two-copies-of-react-error-when-developing-an-external-comp

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The issue is twofold:

  1. You cannot have 2 copies of react loaded.
  2. npm link creates a symlink, however the "require" doesnt respect the symlink and when it tries to navigate up the directory, it never finds the react of the parent project.

Solution:

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...