将 web3 导入 app.js 时出现许多错误

Numerous errors when importing web3 into app.js

尝试将 web3 导入 App.js 出现 9 个错误

import React from "react";
import Web3 from "web3";

function App() {
  return (
    <div className="App">
      <h1>TEST APP</h1>
    </div>
  );
}

export default App;

Compiled with problems:X

ERROR in ./node_modules/cipher-base/index.js 3:16-43

Module not found: Error: Can't resolve 'stream' in '/home/galich/Desktop/projects/mp-test/node_modules/cipher-base'

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.

If you want to include a polyfill, you need to: - add a fallback 'resolve.fallback: { "stream": require.resolve("stream-browserify") }' - install 'stream-browserify' If you don't want to include a polyfill, you can use an empty module like this: resolve.fallback: { "stream": false }

ERROR in ./node_modules/eth-lib/lib/bytes.js 9:193-227

Module not found: Error: Can't resolve 'crypto' in '/home/galich/Desktop/projects/mp-test/node_modules/eth-lib/lib'

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.

If you want to include a polyfill, you need to: - add a fallback 'resolve.fallback: { "crypto": require.resolve("crypto-browserify") }' - install 'crypto-browserify' If you don't want to include a polyfill, you can use an empty module like this: resolve.fallback: { "crypto": false }

ERROR in ./node_modules/web3-eth-accounts/lib/index.js 31:74-91

Module not found: Error: Can't resolve 'crypto' in '/home/galich/Desktop/projects/mp-test/node_modules/web3-eth-accounts/lib'

等等

第一个选项:

使用npm install react-app-rewired node-polyfill-webpack-pluginyarn add react-app-rewired node-polyfill-webpack-plugin.[=18安装NodePolyfillPluginreact-app-rewired =]

现在将 "start": "react-scripts start" 更改为 "start": "react-app-rewired start"

创建一个文件"config-overrides.js"并在里面写入如下代码:

const NodePolyfillPlugin = require("node-polyfill-webpack-plugin");
module.exports = function override(config, _env) {
  config.plugins.push(
    new NodePolyfillPlugin({
      excludeAliases: ["console"],
    })
  );
  return config;
};

现在 "npm start" 和 Hurrah!!!

第二个选项:

而不是像这样导入:

import Web3 from "web3";

像这样导入:

import Web3 from "web3/dist/web3.min.js";

这也将解决您的问题。