coderabbit
V2EX  ›  React

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

  •  
  •   coderabbit · Mar 10, 2020 · 4452 views
    This topic created in 2284 days ago, the information mentioned may be changed or developed.

    用 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 打包发布的?

    8 replies    2020-03-10 21:13:35 +08:00
    Yumwey
        1
    Yumwey  
       Mar 10, 2020
    重新 install react 包试试。
    motoude
        2
    motoude  
       Mar 10, 2020
    别的项目版本是多少是否>=16.8
    coderabbit
        3
    coderabbit  
    OP
       Mar 10, 2020
    @motoude 两边都是最新的 16.13
    KuroNekoFan
        4
    KuroNekoFan  
       Mar 10, 2020
    感觉你得直接上代码网友才能看出点东西
    otakustay
        5
    otakustay  
       Mar 10, 2020
    应该是打了 2 份 react 进去的关系,用 alias 把所有 react 指到一个东西上面吧
    ZZITE
        6
    ZZITE  
       Mar 10, 2020
    多个 react 包的问题吧,看下这个 https://github.com/facebook/react/issues/13991
    lizz666
        7
    lizz666  
       Mar 10, 2020
    赞同楼上,估计是多个 react 包问题,我之前发布组建也有这种问题,我的踩坑记录: https://github.com/lizhongzhen11/dailyGain/issues/57
    coderabbit
        8
    coderabbit  
    OP
       Mar 10, 2020   ❤️ 1
    @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'
    }
    ```
    这样打包后项目引用没报错了!
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5124 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 69ms · UTC 09:30 · PVG 17:30 · LAX 02:30 · JFK 05:30
    ♥ Do have faith in what you're doing.