jonschlinkert / gray-matter

Smarter YAML front matter parser, used by metalsmith, Gatsby, Netlify, Assemble, mapbox-gl, phenomic, vuejs vitepress, TinaCMS, Shopify Polaris, Ant Design, Astro, hashicorp, garden, slidev, saber, sourcegraph, and many others. Simple to use, and battle tested. Parses YAML by default but can also parse JSON Front Matter, Coffee Front Matter, TOML Front Matter, and has support for custom parsers. Please follow gray-matter's author: https://github.com/jonschlinkert

Home Page:https://github.com/jonschlinkert

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

ReferenceError: Buffer is not defined

tomatobybike opened this issue · comments

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

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

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

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

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

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