Webpack 错误 - 无法解析 'crypto'、'http' 和 'https' in Vue.js

Webpack Errors - Cannot Resolve 'crypto', 'http', and 'https' in Vue.js

问题背景

我正在尝试将 Wallet Connect 添加到我们的项目中 (Vue.js),在此处形成:https://docs.walletconnect.com/quick-start/dapps/web3-provider,我使用此命令来安装它。

将其导入我的 js 文件

import Web3 from 'web3'
import WalletConnectProvider from '@walletconnect/web3-provider'

它显示了那些错误:

ERROR  Failed to compile with 7 errors                                                                               
These dependencies were not found:

* crypto in ./node_modules/eth-lib/lib/bytes.js, ./node_modules/web3-eth-accounts/lib/index.js and 1 other
* http in ./node_modules/xhr2-cookies/dist/xml-http-request.js
* https in ./node_modules/xhr2-cookies/dist/xml-http-request.js

To install them, you can run: npm install --save crypto http https

尝试

我安装了那些包。

npm i crypto-browserify
npm i https-browserify
npm i stream-http

然后编辑我的 vue.config.js 个文件:

resolve: {
  fallback: {
    crypto: require.resolve('crypto-browserify'),
    http: require.resolve('stream-http'),
    https: require.resolve('https-browserify'),
  },
},

错误变为:

WebpackOptionsValidationError: Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema.
configuration.resolve has an unknown property 'fallback'. 

These properties are valid:
   object { alias?, aliasFields?, cachePredicate?, cacheWithContext?, concord?, descriptionFiles?, enforceExtension?, enforceModuleExtension?, extensions?, fileSystem?, mainFields?, mainFiles?, moduleExtensions?, modules?, plugins?, resolver?, symlinks?, unsafeCache?, useSyncFileSystemCalls? }

这是我的 package.json 文件:

{
  "dependencies": {
    "@walletconnect/web3-provider": "^1.7.8",
    "crypto-browserify": "^3.12.0",
    "https-browserify": "^1.0.0",
    "os": "^0.1.2",
    "stream": "^0.0.2",
    "stream-http": "^3.2.0",
    "vue": "^2.6.10",
    "web3": "^1.7.3",
  },
  "devDependencies": {
    "@vue/cli-service": "^3.7.0",
    "webpack": "^4.39.3",
    "webpack-bundle-analyzer": "^3.6.0",
    "webpack-dev-server": "^3.11.2",
    "webpack-merge": "^4.2.1",
    "webpack-node-externals": "^1.7.2",
    "webpack-plugin-hash-output": "^3.2.1",
    "webpack-spritesmith": "^1.0.1",
  }
}

而且我的node版本是v10.24.1,暂时还是升级不了

v10.24.1

从上面可以看出,我已经安装了错误(crypto-browserifystream-httphttps-browserify)中建议的软件包,并将它们包含在vue.config.js.

我该如何解决这个问题?

您正在使用 Webpack 4。fallback 选项仅在 Webpack >=5.0.0 之后可用。

对于 Webpack 4,考虑使用 alias 选项。