如何使用 Web3.js 将 Metamask 连接到 Angular 应用程序?

How to connect Metamask to Angular App using Web3.js?

我刚刚开始探索区块链技术,前几天制作了我的第一个智能合约。为了继续,我尝试为智能合约制作前端,但我在使用 web3.js.

将我的 Angular 应用程序连接到 Metamask 时遇到困难

具体来说,我遇到了一个问题,当我尝试为我的 Angular 应用程序提供服务时,它给我这个错误:

Error: ./node_modules/eth-lib/lib/bytes.js Module not found: Error: Can't resolve 'crypto' in 'C:\Users\profile\Desktop\Coding\EthSmartContractProject\Frontend\node_modules\eth-lib\lib'

Error: ./node_modules/eth-lib/lib/bytes.js Module not found: Error: Can't resolve 'stream' in 'C:\Users\profile\Desktop\Coding\EthSmartContractProject\Frontend\node_modules\eth-lib\lib'


这是我的 Blockchain.service.ts,我尝试在 angular 应用程序中处理所有与区块链相关的任务:

import { Injectable } from '@angular/core';
import Web3 from "web3";
declare let window:any;

@Injectable({
  providedIn: 'root'
})
export class ContractService {
  web3: any;
  accounts: Array<String>;

  async loadWeb3() {
    if (window.ethereum) {
        window.web3 = new Web3(window.ethereum);
        await window.ethereum.enable;
    } else if (window.web3) {
        window.web3 = new Web3(window.web3.currentProvider);
    } else {
        window.alert('Non-Ethereum browser detected. You Should consider using MetaMask!');
    }
  }
}


重现步骤:



我尝试实施但没有奏效的解决方案:

我想我知道问题出在哪里,它的依赖项试图导入 nodejs 内置模块。但是我不知道怎么解决。

解决方案:

我没有通过 npm 导入 Web3,而是不得不使用 jsdelivr 将其包含在 index.html 文件中。

<script src="https://cdn.jsdelivr.net/npm/web3@1.3.5/dist/web3.min.js"></script>

这是对我有用的解决方法:

转到:node_modules > @angular-devkit > build-angular > src > webpack > configs > browser.js

在文件末尾,将 node: false 替换为 node: {"stream":true, "crypto":true}

现在,重新提供或重建 angular 应用程序。

在根文件夹上制作 patch.js 并粘贴以下代码并添加到脚本 package.json 中,如下所示:

"postinstall": "node patch.js"
const fs = require('fs')
const f = './node_modules/@angular-devkit/build-angular/src/webpack/configs/browser.js'
fs.readFile(f, 'utf8', function(err, data) {
 if (err) {
   return console.log(err)
 }
 var result = data.replace(/node: false/g, 'node: {crypto: true, stream: true,}')
 fs.writeFile(f, result, 'utf8', function(err) {
   if (err) return console.log(err)
 })
});

通过在 tsconfig.json 中添加此内容解决了此问题:

{
  "compilerOptions": {
    "paths" : {
      "crypto": ["./node_modules/crypto-browserify"],
      "stream": ["./node_modules/stream-browserify"],
      "assert": ["./node_modules/assert"],
      "http": ["./node_modules/stream-http"],
      "https": ["./node_modules/https-browserify"],
      "os": ["./node_modules/os-browserify"],
    }
  }
}

不要忘记安装所需的依赖项:

npm install crypto-browserify stream-browserify assert stream-http https-browserify os-browserify

(有关详细信息,请参阅 https://github.com/ChainSafe/web3.js/issues/4070#issuecomment-843193781