V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
Chism
V2EX  ›  React

[经验] React 17 和 comsjs 冲突的解决

  •  
  •   Chism · 2022-02-25 13:16:17 +08:00 · 1582 次点击
    这是一个创建于 793 天前的主题,其中的信息可能已经有所发展或是发生改变。

    Bug 描述

    • react 17 引入 @cosmjs/amino 运行,报错如下:

      BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
      This is no longer the case. Verify if you need this module and configure a polyfill for it.
      

    复现步骤

    1. 新建 react 项目

      npx create-react-app react17-cosmjs-conflect
      
    2. 安装 @cosmjs/amino

      npm i @cosmjs/amino
      
    3. 在 /src/index.js 引入 @cosmjs/stargate

      import React from 'react';
      import ReactDOM from 'react-dom';
      import './index.css';
      import App from './App';
      import reportWebVitals from './reportWebVitals';
      
      import {decodeBech32Pubkey} from '@cosmjs/amino'
      console.log(decodeBech32Pubkey)
      
      ReactDOM.render(
        <React.StrictMode>
          <App />
        </React.StrictMode>,
        document.getElementById('root')
      );
      reportWebVitals();
      
    4. 运行

      npm run start
      
    5. 报错如开篇所示

    Bug 原因

    npx create-react-app 命令创建的 React17 默认调用的是 webpack5 ,相比 webpack4 ,精简了很多自带的包,需要手动安装才行

    解决方法 1

    将 react-scripts 由默认的 5.0.0 改为 4.0.3 ,npm i [email protected] 即可

    解决方法 2

    1. 将 react 17 的 webpack config 从 node_modules 里暴露出来,如果提示 git uncommitted 就先 commit 一下

      npm run eject
      
    2. 安装这 4 个包:

      npm i stream-browserify buffer path-browserify crypto-browserify
      
    3. 根据报错提示配置 /config/webpack.config.js

      搜索“resolve:”,在 resolve 内添加 fallback 节点,内容如下

      fallback: {
        "stream": require.resolve("stream-browserify"),
        "buffer": require.resolve("buffer/"),
        "path": require.resolve("path-browserify"),
        "crypto": require.resolve("crypto-browserify")
      }
      
    4. 这时候再 npm run start 运行就没有 error 了,但是有 40 个 warning ,都是关于 cosmjs 缺少 source map 的,如果不想看到这个错误,可以在跟 resolve 节点同级的地方添加以下属性,搜索“resolve:”,在上一行放:

      ignoreWarnings: [/Failed to parse source map/],
      

    提示:如果没有将 webpack config 从 node_modules 里暴露出来,直接在项目根目录创建 webpack.config.js 文件去配置无法解决此 bug

    2 条回复    2022-02-25 16:11:52 +08:00
    hronro
        1
    hronro  
       2022-02-25 15:37:49 +08:00
    你都发现原因了,你就应该清楚,这个问题和 React 以及 React 17 没啥关系
    Chism
        2
    Chism  
    OP
       2022-02-25 16:11:52 +08:00 via Android
    @hronro 懂你的意思,主要还是 webpack5 导致,这算是一个特例,刚好这几天碰到,顺手记录
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1330 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 17:29 · PVG 01:29 · LAX 10:29 · JFK 13:29
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.