Uncaught ReferenceError: Buffer is not defined
在写 defi 项目过程中,遇到了下面这个问题:
index-DktoYhwa.js:1220 Uncaught ReferenceError: Buffer is not defined
本地开发的时候没发现,在打包预览部署的时候会出现。原因是钱包的相关依赖使用了 Buffer 这个 Node 内置模块。
Since browsers do not support Node’s Core Modules, packages that use them must be polyfilled to function in browser environments. In an attempt to prevent runtime errors, Vite produces errors or warnings when your code references builtin modules such as fs or path.
解决方案是添加 vite-plugin-node-polyfills 插件来解决:
import { nodePolyfills } from 'vite-plugin-node-polyfills'
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import tailwindcss from '@tailwindcss/vite'
import path from 'path'
import svgr from 'vite-plugin-svgr'
export default defineConfig(({ command }) => {
const plugins = [react(), tailwindcss(), svgr()]
// 仅在构建时添加 nodePolyfills 插件
if (command === 'build') {
plugins.push(
nodePolyfills({
globals: {
Buffer: 'build', // can also be 'build', 'dev', or false
global: 'build',
process: 'build',
},
})
)
}
return {
server: {
host: true,
port: 5173,
strictPort: true,
allowedHosts: [],
},
plugins,
resolve: {
alias: {
'@': path.resolve(__dirname, './src'),
},
},
define: {
'process.env': {},
},
}
})