Search code examples
angularethereumweb3jsmetamask

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

  • 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/[email protected]/dist/web3.min.js"></script>