react hook 组件 webpack 打包后不能使用

2020-03-10 10:15:16 +08:00
 coderabbit

用 hook 写的组件,打包后在别的项目使用,然后报!

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

然后我把 hook 里的 useState useRef 去掉就一个纯函数式组件。打包后再引用没问题!然后我又把组件直接放在项目里使用没有问题,唯独我组件中使用了 useState 打包引用就会报上面的错!还是说 hook 组件是不能用 webpack 打包发布的?

3594 次点击
所在节点    React
8 条回复
Yumwey
2020-03-10 10:18:03 +08:00
重新 install react 包试试。
motoude
2020-03-10 10:20:54 +08:00
别的项目版本是多少是否>=16.8
coderabbit
2020-03-10 10:24:26 +08:00
@motoude 两边都是最新的 16.13
KuroNekoFan
2020-03-10 11:01:24 +08:00
感觉你得直接上代码网友才能看出点东西
otakustay
2020-03-10 11:02:22 +08:00
应该是打了 2 份 react 进去的关系,用 alias 把所有 react 指到一个东西上面吧
ZZITE
2020-03-10 11:31:32 +08:00
多个 react 包的问题吧,看下这个 https://github.com/facebook/react/issues/13991
lizz666
2020-03-10 14:43:48 +08:00
赞同楼上,估计是多个 react 包问题,我之前发布组建也有这种问题,我的踩坑记录: https://github.com/lizhongzhen11/dailyGain/issues/57
coderabbit
2020-03-10 21:13:35 +08:00
@ZZITE @lizz666 谢谢解决了!
```
externals: {
'react': 'React',
'react-dom': 'ReactDOM',
'react-router-dom': 'ReactRouterDOM'
}
```
之前我是这样排除的。我发现包里确实没有打包进去这些东西。后面看了 issues
```
react: {
root: 'React',
commonjs2: 'react',
commonjs: 'react',
amd: 'react'
},
'react-dom': {
root: 'ReactDOM',
commonjs2: 'react-dom',
commonjs: 'react-dom',
amd: 'react-dom'
},
'react-router-dom': {
root: 'ReactRouterDOM',
commonjs2: 'react-router-dom',
commonjs: 'react-router-dom',
amd: 'react-router-dom'
}
```
这样打包后项目引用没报错了!

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/651421

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX