Search code examples
reactjstypescriptviteweb3jsweb3-react

Error when using Web3.js with Vite and TypeScript in a React.js Project: "Module 'events' has been externalized for browser compatibility"


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.


Solution

  • 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.