Search code examples
reactjstypescriptviteweb3js

How can I use Buffer, process in Vite app?


I'm using wagmi in typescript react app setup by Vite.

I got some issue ex:

"global is not defined", "buffer is not defined"

And I tried it again with some code in main.tsx:

import { Buffer } from 'buffer';
import process from 'process';

window.global = window;
window.Buffer = Buffer;
window.process = process;

But I still get some error ex: "Module "process" has been externalized for browser compatibility. Cannot access "process.versions" in client code."

Error will occur when I connect to coinbase or walletconnect connector.

My vite.config.ts

import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
//import Buffer from 'buffer';

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [react()],
  server: {
    port: 5000,
  },
  resolve: {
    alias: [{ find: '@', replacement: '/src' }],
  },
  define: {
    // global: 'window',
    // Buffer: Buffer,
    // process: process,
  },
});

Solution

  • To get buffer and process working, do the following:

    1. install buffer and process: npm install buffer process

    2. edit index.html to add some js:

    <!-- node // buffer-->
    <script>window.global = window;</script>
    <script type="module">
        import { Buffer } from "buffer/"; // <-- no typo here ("/")
        import process from "process";
       
        window.Buffer = Buffer;
        window.process = process;
    </script>
    
    1. edit your vite.config.js to add resolve.alias options:
    export default defineConfig({
      [...]
    
      resolve: {
        alias: {
          process: "process/browser"
        }
      }
    })
    
    1. in your component, import buffer (note the /):
    import { Buffer } from 'buffer/'
    
    [...]
    

    Live example on stackblitz, open your console devtools on the preview, and look at the Uint8Array debug line.

    You can give a read to my old answer for further setup like for process, events or even crypto.