Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ReferenceError: Buffer is not defined #143

Open
tomatobybike opened this issue May 6, 2022 · 6 comments
Open

ReferenceError: Buffer is not defined #143

tomatobybike opened this issue May 6, 2022 · 6 comments

Comments

@tomatobybike
Copy link

when i use gray-matter in vite react project, found this error:

react_devtools_backend.js:3973 ReferenceError: Buffer is not defined
    at Object.exports2.toBuffer (utils.js:36:38)
    at module2.exports (to-file.js:28:36)
    at matter (index.js:34:14)
    at getFile (Docs.jsx:154:17)

how to fix

@tomatobybike
Copy link
Author

tomatobybike commented May 6, 2022

Install this library

yarn add @esbuild-plugins/node-globals-polyfill

add this import to your vite.config.js

and add this in your vite.config.js

import { NodeGlobalsPolyfillPlugin } from '@esbuild-plugins/node-globals-polyfill'
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
                })
            ]
        }
    }
}

@TeemuKoivisto
Copy link

Wow rarely I find solutions that work straight away, thanks @tomatobybike !

@segevfiner
Copy link

Would be nicer if this library was compatible with the browser to begin with, or add a browser build defined in the package.json

@segevfiner
Copy link

It seems optimizeDeps isn't run on vite build...

@andrewspy
Copy link

vite-plugin-node-polyfills should solve both dev/build problem.
See: https://www.npmjs.com/package/vite-plugin-node-polyfills

@transtone
Copy link

if use nuxtjs, see nuxt/nuxt#25016

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants