tronprotocol / tronweb

Javascript API Library for interacting with the TRON Network
MIT License
388 stars 259 forks source link

Module "crypto" has been externalized for browser compatibility: Vite + React #531

Closed theprashantparihar closed 1 week ago

theprashantparihar commented 2 weeks ago

Using react with vite, I am able to connect to tronlink but when it comes to fetching balance getting a warning: 'Module "crypto" has been externalized for browser compatibility. Cannot access crypto.createHash in client code' and an error 'Invalid address'

Tried fixing it by following https://github.com/tronprotocol/tronweb/issues/488, installed the three packages added them in viteconfig but then got this error: 'ReferenceError: global is not defined at node_modules/randombytes/browser.js' tried adding window.global ||= window; but still the error persists

start940315 commented 2 weeks ago

window.global ||= window should be added before all code which means you may need to add a script at the beginning of index.html. Just like below:

<script>window.global ||= window;</script>
theprashantparihar commented 2 weeks ago
Screenshot 2024-07-03 at 1 53 43 PM

This is my folder structure, I tried adding window.global ||= window in main.jsx, but got the error: global is not defined, then installed the global package and defined it in viteConfig, then got another error: process is not defined. Did the same, installed process and defined it in viteConfig. Then got 'Cannot read properties of undefined (reading 'slice')' this error.

start940315 commented 1 week ago

Add it in your index.html file, not in main.jsx.

theprashantparihar commented 1 week ago

Done, This is how the index.html looks now

Screenshot 2024-07-04 at 3 28 41 PM

After this got an error 'The file does not exist at "/Users/prashant/Documents/crypto_bridge/crypto_bridge/node_modules/.vite/deps/chunk-YIT4L4ID.js?v=92fa8ba1" which is in the optimize deps directory. The dependency might be incompatible with the dep optimizer. Try adding it to optimizeDeps.exclude.' To solve this I excluded it in viteConfig: optimizeDeps: { exclude: ['chunk-PAC5ASQS'] // Add the problematic dependency here }

and now getting 'ReferenceError: process is not defined at node_modules/browserify-sign/node_modules/readable-'

start940315 commented 1 week ago

Can your code work? In most scenarios your code will work. And I don't have your code, don't know what's wrong with it.

theprashantparihar commented 1 week ago

It is not working, I have attached my package.json and viteConfig. Do you see anything wrong where?

Screenshot 2024-07-05 at 9 30 31 PM Screenshot 2024-07-05 at 9 30 42 PM

I would really appreciate if we can connect, I will show you the code. @theprashantparihar is my tg username

theprashantparihar commented 1 week ago

Update: the issue got fixed by adding below to the index.html:

Thanks @start940315 really appreciate your help.