我刚刚开始探索Blockchain技术,并在前几天签订了我的第一份智能合同。为了继续,我已经尝试为智能合同做一个前端,但我面临着使用web3.js连接我的角应用程序到Metamask的困难。
具体来说,我遇到了一个问题,当我试图为我的角度应用程序服务时,它给了我这个错误:
'C:\Users\profile\Desktop\Coding\EthSmartContractProject\Frontend\node_modules\eth-lib\lib‘错误:./node_
/eth-lib/lib/bytes.js模块未找到:错误:无法解析'C:\Users\profile\Desktop\Coding\EthSmartContractProject\Frontend\node_modules\eth-lib\lib’中的“”错误:./node_/eth/lib/bytes.js模块未找到:错误:无法解析‘C:\Users\profile\Desktop\Coding\EthSmartContractProject\Frontend\node_modules\eth-lib\lib’中的“流”
这里是我的Blockchain.service.ts,在这里我尝试处理角应用程序中与区块链相关的所有任务:
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!');
}
}
}
复制步骤:
F 212
我试图实施但没有奏效的解决办法:
package.json
"browser": { "crypto": false }添加到自定义webpack中,并试图通过启用crypto: true或其他什么来“修补”行为。我想我知道问题来自哪里,它的依赖项试图导入内置于模块中的nodejs。但是我不知道怎么解决它。
发布于 2021-05-09 12:41:18
解决方案:
我没有通过npm导入Web3,而是使用jsdelivr将其包含在index.html文件中。
<script src="https://cdn.jsdelivr.net/npm/web3@1.3.5/dist/web3.min.js"></script>发布于 2021-08-03 05:01:33
在根文件夹上创建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)
})
});发布于 2021-11-05 18:46:56
通过在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 )
https://stackoverflow.com/questions/67355967
复制相似问题