简体   繁体   中英

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

I have just started exploring Blockchain technologies and made my first smart contract the other day. To continue, I have tried to make a frontend for the smart contract but I am facing difficulty connecting my Angular App to Metamask using web3.js.



Specifically, I am encountering an issue where when I try to serve my Angular application it give me this error:

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'


Here is my Blockchain.service.ts where I try an handle all the blockchain related tasks in the angular app:

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!');
    }
  }
}


Steps to reproduce:

  • ng new Project
  • npm i web3
  • Create the Blockchain service
  • ng serve


Solutions I have tried to implement but did not work:

  • Adding "browser": { "crypto": false } to package.json
  • Using a custom webpack and trying to 'patch' the behaviour by enabling crypto: true or something.

I think I know where the issue is coming from, its dependencies trying to import nodejs built in modules. But I dont know how to fix it.

Solution:

Instead of importing Web3 through npm, I had to include it in the index.html file using jsdelivr.

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

Make patch.js on root folder and paste the following code and add in script package.json like this:

"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)
 })
});

Here's a workaround that worked for me:

Go to: node_modules > @angular-devkit > build-angular > src > webpack > configs > browser.js

At the end of the file, replace node: false with node: {"stream":true, "crypto":true}

Now, re-serve or rebuild the angular app.

Resolved this issue by adding this in 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"],
    }
  }
}

Don't forget to install the required dependencies:

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

( see https://github.com/ChainSafe/web3.js/issues/4070#issuecomment-843193781 for more informations )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM