简体   繁体   中英

Buffer is not defined in React-vite

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

错误截图

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

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'

I also landed here and I tried Николай Сычев solution from 2015 but it didn't work.

Instead, in the year 2022 I succeeded by

  1. simply installing buffer as a dev dependency yarn add buffer (use npm equivalent if you use npm)

  2. and then adding it to the global scope in the index.html like this:

<html lang="en">
  <head>
    <script type="module">
      import { Buffer } from "buffer";
      window.Buffer = Buffer;
    </script>   
   ...

It also works for similar dependencies like process which you'd import in the index.html like this:

      import process from "process";
      window.process = process; 

Maybe the original poster may update the accepted answer, because that approach using @esbuild-plugins/node-globals-polyfill does not seem to be the recommended way any more (when trying to polyfill process, I'd get some weird "redeclaration" errors).

The way I am proposing here seems to be the state of the art approach.

For me the above configuration did not work, I had to make changes in 3 files, in vite.config.ts, index.html and adding packages

1.Install Packages

yarn install process util buffer events
yarn add @esbuild-plugins/node-modules-polyfill

2.Update vite.config

import GlobalPolyFill from "@esbuild-plugins/node-globals-polyfill";
import react from "@vitejs/plugin-react";
import { resolve } from "path";
import { defineConfig } from "vite";

export default defineConfig({
    plugins: [react()],
    optimizeDeps: {
        esbuildOptions: {
            define: {
                global: "globalThis",
            },
            plugins: [
                GlobalPolyFill({
                    process: true,
                    buffer: true,
                }),
            ],
        },
    },
    resolve: {
        alias: {
            process: "process/browser",
            stream: "stream-browserify",
            zlib: "browserify-zlib",
            util: "util",
        },
    },
});

3.Update index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <link rel="icon" type="image/svg+xml" href="/src/assets/images/favicon.svg" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Vite App</title>
  <script>
    window.global = window;
  </script>
  <script type="module">
    import process from "process";
    import EventEmitter from "events";
    import {Buffer} from "buffer";
    window.Buffer = Buffer;
    window.process = process;
    window.EventEmitter = EventEmitter;
  </script>
</head>

<body>
  <div id="root"></div>
  <script type="module" src="./src/index.js"></script>
</body>
</html>

Another approach is:

npm i -D rollup-plugin-polyfill-node

Then update vite.config.ts with the following:

import nodePolyfills from 'rollup-plugin-polyfill-node'
rollupOptions: {
  plugins: [
    // ...plugins
    nodePolyfills(),
  ],
  // ...rollupOptions
},

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM