React-vite 中没有定义 Buffer

Buffer is not defined in React-vite

从 CRA 迁移后未定义缓冲区(创建 React 应用程序)

"邀请": "^2.7.12"

我尝试添加插件,为Buffer添加定义,但是没有用。

const viteConfig = defineConfig({
/*    define: {
        "Buffer": {}
    },*/
    plugins: [reactRefresh(), react()],
    build: {
        rollupOptions: {
            input: {
                main: resolve('index.html'),
            },
        },
    },
    clearScreen: false
});

安装这个库

@esbuild-plugins/node-globals-polyfill

并将其添加到您的 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
                })
            ]
        }
    }
})

将此库导入添加到您的 vite.config.js

import { NodeGlobalsPolyfillPlugin } from '@esbuild-plugins/node-globals-polyfill'