【发布时间】:2021-04-21 10:39:11
【问题描述】:
我正在尝试使用 Angular 创建以太坊 dapp。
我在关注那篇文章:
https://medium.com/blockchain-developer/learn-how-to-create-your-own-dapp-with-angular-9-part-iv-truffle-7704dc4269ab
但是,当我使用npm install --save web3 将 web3 添加到应用程序时,
并在代码中调用它,我遇到了以下问题:
Error: ./node_modules/swarm-js/node_modules/eth-lib/lib/bytes.js
Module not found: Error: Can't resolve 'crypto' in '/home/szymon/dev/dapp/node_modules/swarm-js/node_modules/eth-lib/lib'
Error: ./node_modules/web3-eth-accounts/node_modules/eth-lib/lib/bytes.js
Module not found: Error: Can't resolve 'crypto' in '/home/szymon/dev/dapp/node_modules/web3-eth-accounts/node_modules/eth-lib/lib'
Error: ./node_modules/web3-eth-accounts/src/index.js
Module not found: Error: Can't resolve 'crypto' in '/home/szymon/dev/dapp/node_modules/web3-eth-accounts/src'
Error: ./node_modules/web3-providers-http/src/index.js
Module not found: Error: Can't resolve 'http' in '/home/szymon/dev/dapp/node_modules/web3-providers-http/src'
Error: ./node_modules/xhr2-cookies/dist/xml-http-request.js
Module not found: Error: Can't resolve 'http' in '/home/szymon/dev/dapp/node_modules/xhr2-cookies/dist'
Error: ./node_modules/web3-providers-http/src/index.js
Module not found: Error: Can't resolve 'https' in '/home/szymon/dev/dapp/node_modules/web3-providers-http/src'
Error: ./node_modules/xhr2-cookies/dist/xml-http-request.js
Module not found: Error: Can't resolve 'https' in '/home/szymon/dev/dapp/node_modules/xhr2-cookies/dist'
Error: ./node_modules/xhr2-cookies/dist/xml-http-request.js
Module not found: Error: Can't resolve 'os' in '/home/szymon/dev/dapp/node_modules/xhr2-cookies/dist'
Error: ./node_modules/cipher-base/index.js
Module not found: Error: Can't resolve 'stream' in '/home/szymon/dev/dapp/node_modules/cipher-base'
Error: ./node_modules/keccak/lib/api/keccak.js
Module not found: Error: Can't resolve 'stream' in '/home/szymon/dev/dapp/node_modules/keccak/lib/api'
Error: ./node_modules/keccak/lib/api/shake.js
Module not found: Error: Can't resolve 'stream' in '/home/szymon/dev/dapp/node_modules/keccak/lib/api'
我该怎么办? Web3 是这样调用的:
let Web3 = require('web3');
export class TransferService {
constructor() {
if (typeof window.web3 !== undefined) {
this.web3 = window.web3.currentProvider;
} else {
this.web3 = new Web3.providers.HttpProvider('http://localhost:7545');
}
window.web3 = new Web3(window.ethereum);
this.enable = this.enableMetaMaskAccount();
}
}
【问题讨论】:
-
你是如何尝试在 Angular 代码中调用
web3的? -
查看原帖,已编辑。
-
如果您从浏览器调用它,请尝试使用
import Web3 from 'web3';而不是let Web3 = require('web3'); -
在浏览器的情况下使用
import是一个好点。但是,如果web3是一个纯 JavaScript 库,那么使用import可能是不够的。 JavaScript 文件需要列在angular.json中的architect->build->scripts[]数组中。 -
使用
import代替require并不能解决任何问题。