【发布时间】:2021-07-25 02:24:00
【问题描述】:
我刚刚开始探索区块链技术,并在前几天制作了我的第一个智能合约。为了继续,我尝试为智能合约制作前端,但我在使用 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!');
}
}
}
重现步骤:
- ng 新项目
- npm i web3
- 创建区块链服务
- ng 服务
我尝试实施但没有奏效的解决方案:
- 在 package.json 中添加
"browser": { "crypto": false } - 使用自定义 webpack 并尝试通过启用
crypto: true或其他方式“修补”该行为。
我想我知道问题出在哪里,它的依赖项试图导入内置模块的 nodejs。但我不知道如何解决它。
【问题讨论】:
标签: angular ethereum web3 metamask