ReactJS项目调用keccak256时出现Uncaught ReferenceError: Buffer is not defined错误的解决求助
Got it, let's break down why this error is happening and how to fix it quickly.
The keccak256 library relies on Node.js's native Buffer API, but browser environments (like your React app) don't include a global Buffer object by default. That's exactly why you're hitting the ReferenceError: Buffer is not defined when calling keccak256(v) in your map function.
Here's how to resolve this step-by-step:
Step 1: Install the buffer polyfill
First, we need to add a browser-compatible implementation of Buffer to your project:
npm install buffer # Or if you use Yarn: yarn add buffer
Step 2: Add the polyfill to your React component
Import the Buffer from the installed package and attach it to the global window object so keccak256 can access it. Here's your updated App.js with the fix:
import './App.css'; import { useState, useEffect } from 'react'; import { ethers } from 'ethers'; import { MerkleTree } from 'merkletreejs'; import keccak256 from 'keccak256'; import { Buffer } from 'buffer'; import tokens from './tokens.json'; // Polyfill Buffer for the browser environment if (typeof window !== 'undefined') { window.Buffer = window.Buffer || Buffer; } function App() { function isWhitelisted() { // Simplify your array mapping (no need for a separate tab variable) const leaves = tokens.map(token => keccak256(token.address)); console.log('Merkle Leaves:', leaves); const tree = new MerkleTree(leaves, keccak256, { sort: true }); const targetLeaf = keccak256("0x7D8a1f6A5efc16E88FeF87E7745EAc2F5Cbc88D7"); const proof = tree.getHexProof(targetLeaf); // Optional: Verify if the address is actually in the whitelist const isAddressWhitelisted = tree.verify(proof, targetLeaf, tree.getRoot()); console.log('Proof:', proof); console.log('Is address whitelisted?', isAddressWhitelisted); } return ( <div className="App"> <button onClick={isWhitelisted}>TEST WHITELIST</button> </div> ); } export default App;
What's happening here?
By importing the buffer package and attaching it to window.Buffer, we're providing the keccak256 library with the exact Buffer implementation it expects, just like it would get in a Node.js environment. This eliminates the reference error entirely.
I also cleaned up your code a bit (removed the unnecessary tab variable) and added an optional verification step to check if the target address is actually in your whitelist, which might be useful for testing.
内容的提问来源于stack exchange,提问作者Ben BK

