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