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



我刚刚开始探索区块链技术,前几天我制作了第一个智能合约。为了继续,我试图为智能合约做一个前端,但我在使用web3.js.将我的Angular应用程序连接到Metamask时遇到了困难

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

错误:/找不到node_modules/eth lib/lib/bytes.js模块:错误:无法解析"C:\Users\profile\Desktop\Coding\EthSmartContractProject\Frontend\node_modules\eth lib\lib"中的"crypto">

错误:/找不到node_modules/eth lib/lib/bytes.js模块:错误:无法解析"C:\Users\profile\Desktop\Coding\EthSmartContractProject\Frontend\node_modules\eth lib\lib"中的"stream">

这是我的Blockchain.services.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!');
}
}
}


复制步骤:

  • ng新项目
  • npm i web3
  • 创建区块链服务
  • ng发球

我尝试过实施但没有成功的解决方案:

  • "browser": { "crypto": false }添加到package.json
  • 使用自定义的webpack并尝试通过启用crypto: true或其他方式来"修补"行为

我想我知道问题来自哪里,它的依赖关系试图导入模块中内置的nodejs。但我不知道怎么修。

在根文件夹上制作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)
})
});

解决方案:

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

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

通过在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获取更多信息(

这里有一个对我有效的解决方法:

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

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

现在,重新服务或重建angular应用程序。

最新更新