Web3 formatter.js 加载问题

Web3 formatter.js loading issue

我正在尝试使用 NextJS 创建一个小型以太坊区块链应用程序。

导入 Web3 导致了一些问题

ModuleParseError: Module parse failed: C:\Path\node_modules\web3-core-helpers\lib\formatters.js Unexpected token (296:20)
You may need an appropriate loader to handle this file type.
|     // If options !== undefined, don't blow out existing data
|     if (options.fromBlock === undefined)
|         options = { ...options, fromBlock: 'latest' };
|     if (options.fromBlock || options.fromBlock === 0)
|         options.fromBlock = inputBlockNumberFormatter(options.fromBlock);
    at C:\Path\node_modules\webpack\lib\NormalModule.js:303:19
    at C:\Path\node_modules\webpack\lib\NormalModule.js:209:11
    at C:\Path\node_modules\loader-runner\lib\LoaderRunner.js:373:3
    at iterateNormalLoaders (C:\Path\node_modules\loader-runner\lib\LoaderRunner.js:214:10)
    at C:\Path\node_modules\loader-runner\lib\LoaderRunner.js:205:4
    at C:\Path\node_modules\enhanced-resolve\lib\CachedInputFileSystem.js:70:14
    at processTicksAndRejections (internal/process/task_queues.js:75:11)

import Web3 from "web3";是根本原因

import Web3 from "web3";

const web3 = new Web3(window.ethereum);

export default web3;

这是我的 package.json

{
  "name": "myproject",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "mocha",
    "dev": "next dev"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@truffle/hdwallet-provider": "^1.2.2",
    "fs-extra": "^9.1.0",
    "ganache-cli": "^6.12.2",
    "mocha": "^8.3.0",
    "next": "^4.1.4",
    "react": "^16.14.0",
    "react-dom": "^16.14.0",
    "solc": "^0.4.17",
    "web3": "^1.3.4"
  }
}

我需要其他模块吗? 我注意到在使用 npx create-next-app 创建应用程序时,同样的导入工作正常,但我想使用特定版本,所以我只在我的节点项目中使用 npm install --save next@4.1.4 react@16 react-dom@16

我 运行 遇到了同样的问题,看来我可以通过使用命令“npm install next@10.0.7”更新 next 来解决它

我在 运行“npm audit”之后找到了这个解决方案,它推荐使用上述命令来解决各种依赖性问题。

使用 Web3 v1.2.9

对我有用!

enter image description here

使用Object.assgn替换... 有效

此错误的原因在消息中很明显,可能是因为较新的 javascript 中的 ... 表示法,因为您使用的下一个是旧的,它没有意义它的。你有 3 个选项(我做了第三个)

  1. 使用 options = Object.assign(options, {fromBlock: latest})
  2. 将那段代码更改为旧语法
  3. 使用更新的 next 可以实现新的语法
  4. 使用不使用新语法的旧 web3,@1.2.9 有效。别忘了npm install