Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

使用npm-link开发react组件库,遇到“have multiple copies of React loaded”的坑 #19

Open
varHarrie opened this issue Aug 7, 2017 · 0 comments

Comments

@varHarrie
Copy link
Owner

最近把一些在项目中用到的组件抽离出来,封装成一个组件库,然后关联出去npm link,再在原项目中通过npm link my-components的方式关联回这个组件库。

运行时发现一个错误:

Uncaught Invariant Violation: addComponentAsRefTo(...): Only a ReactOwner can have refs. You might be adding a ref to a component that was not created inside a component's render method, or you have multiple copies of React loaded (details: fb.me/react-refs-must-have-owner).

检查过后并没用发现在render函数以外的地方用到ref,于是怀疑是不是have multiple copies of React loaded

这里找到两种解决方案:

  1. 修改当前项目的webpack配置:
resolve: {
  alias: {
    react: path.resolve('./node_modules/react'),
  },
}
  1. 利用npm-link的方式:
# 连接组件库
cd my-app
npm link ../my-components

# 将项目中的react连接到组件库
cd ../my-components
npm link ../my-app/node_modules/react

这两种方法都达到使react都指向同一份引用,后者更适用于库的开发。

@varHarrie varHarrie added this to the Posts milestone Aug 5, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant