Search code examples
reactjsbuffervite

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
});

Solution

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