skip to Main Content

I’m developing a React.js project with TypeScript managed with Vite, and I’m facing an issue when trying to integrate Web3.js for communication with Ethereum Smart Contracts. The project is set up to connect to a local Ethereum blockchain running on Ganache at http://localhost:7545.

I installed Web3.js using npm install web3 and attempted to create a Web3 instance like this:

import Web3 from 'web3';

const web3 = new Web3(Web3.givenProvider || 'http://localhost:7545');

However, as soon as I call any Web3.js functions, such as const web3 = new Web3(Web3.givenProvider || 'http://localhost:7545'); or Web3.version, I receive the following warnings and errors in the console:

  1. Module "events" has been externalized for browser compatibility. Cannot access "events.EventEmitter" in client code. See http://vitejs.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.
  2. Uncaught TypeError: Class extends value undefined is not a constructor or null at common.ts:58:29 (anonymous) @ common.ts:58

This is a React.js project managed with Vite, and I have limited experience with modern frontend technology stacks. I’m wondering if there are additional configurations or setups I need to perform to successfully integrate Web3.js into my frontend project.

Any guidance, suggestions, or insights on how to resolve these issues and correctly configure Web3.js within my React.js/Vite/TypeScript project would be highly appreciated.

2

Answers


  1. Chosen as BEST ANSWER

    For the sake of completeness here are the steps that solved my problem for the community:

    1. Run in the project directory npm install --save-dev vite-plugin-node-polyfills in order to install vite-plugin-node-polyfills.
    2. Add the nodePolyfills-plugin into your vite.config.ts-file:
    import { defineConfig } from 'vite'
    import react from '@vitejs/plugin-react'
    import {nodePolyfills} from 'vite-plugin-node-polyfills';
    
    // https://vitejs.dev/config/
    export default defineConfig({
      plugins: [react(), nodePolyfills()],
    })
    

  2. Since browsers do not support Node’s Core Modules, packages that use them must be polyfilled to function in browser environments. In an attempt to prevent runtime errors, Vite produces errors or warnings when your code references builtin modules such as fs or path.

    You are missing node polyfills. You can add this by installing vite-plugin-node-polyfills and add events polyfill to your vite.config. Simply follow README on the npm page and you should be fine.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search