5

After having declared and done all the config files, when I start the server I get Buffer not defined and the error points to an npm module. Uncaught ReferenceError: Buffer is not definedat node_modules/jsesc/jsesc.js

Elyess Eleuch
  • 141
  • 1
  • 5
  • I am having the exact same problem (on vite 2.6.14 and plugin-react 1.1.3). Any luck in finding the solution ? – flieks Jan 04 '22 at 21:57
  • @flieks I wrote this in vite.config.js defineConfig({ define: { **"Buffer": {},** ..... This way I managed to get the error away but still not sure if it's the right thing to do because I still cannot test the app as I have another problem to deal with which is "Module "fs" has been externalized for browser compatibility and cannot be accessed in client code" – Elyess Eleuch Jan 05 '22 at 10:11
  • Have you solved the issue? I'm having the exact same problem rn. – NEWBIEHERE Feb 25 '22 at 00:55

1 Answers1

1

You can make the following changes to fix the issue, in vite.config.ts , index.html and adding packages

1.Install Packages

yarn add 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 rollupNodePolyFill from "rollup-plugin-node-polyfills";
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>
Goutham J.M
  • 1,726
  • 12
  • 25