Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Buffer is not defined in React-vite

Buffer is not defined after migrating from CRA(create react app)

Screenshot of error

"vite": "^2.7.12"

I try to add plugins, add define for Buffer, but it's not work.

const viteConfig = defineConfig({
/*    define: {
        "Buffer": {}
    },*/
    plugins: [reactRefresh(), react()],
    build: {
        rollupOptions: {
            input: {
                main: resolve('index.html'),
            },
        },
    },
    clearScreen: false
});
like image 413
Николай Сычев Avatar asked Aug 30 '25 15:08

Николай Сычев


1 Answers

Install this library

@esbuild-plugins/node-globals-polyfill

and add this in your vite.config.js

export default defineConfig({
    // ...other config settings
    optimizeDeps: {
        esbuildOptions: {
            // Node.js global to browser globalThis
            define: {
                global: 'globalThis'
            },
            // Enable esbuild polyfill plugins
            plugins: [
                NodeGlobalsPolyfillPlugin({
                    buffer: true
                })
            ]
        }
    }
})

add this libary import to your vite.config.js

import { NodeGlobalsPolyfillPlugin } from '@esbuild-plugins/node-globals-polyfill'
like image 136
Николай Сычев Avatar answered Sep 05 '25 07:09

Николай Сычев