Vite搭建的TypeScript React Wagmi应用全局变量与process报错求助
解决Vite+React+TypeScript中wagmi的全局变量及process相关报错
问题场景
在Vite搭建的TypeScript React应用中使用wagmi时,先后遇到以下报错:
- "global is not defined"、"buffer is not defined"
- 连接Coinbase或WalletConnect连接器时触发:"Module 'process' has been externalized for browser compatibility. Cannot access 'process.versions' in client code."
尝试在main.tsx中手动挂载全局变量后仍未解决,相关代码及配置如下:
尝试的main.tsx代码:
import { Buffer } from 'buffer'; import process from 'process'; window.global = window; window.Buffer = Buffer; window.process = process;
当前vite.config.ts配置:
import { defineConfig } from 'vite'; import react from '@vitejs/plugin-react'; export default defineConfig({ plugins: [react()], server: { port: 5000, }, resolve: { alias: [{ find: '@', replacement: '/src' }], }, define: { // global: 'window', // Buffer: Buffer, // process: process, }, });
解决方案
1. 安装依赖包
先安装所需的polyfill及rollup插件:
npm install buffer process npm install rollup-plugin-node-polyfills --save-dev
2. 修改vite.config.ts配置
更新配置文件,添加全局定义、resolve fallback及rollup插件配置:
import { defineConfig } from 'vite'; import react from '@vitejs/plugin-react'; export default defineConfig({ plugins: [react()], server: { port: 5000, }, resolve: { alias: [{ find: '@', replacement: '/src' }], fallback: { "buffer": require.resolve("buffer"), "process": require.resolve("process/browser") } }, define: { 'process.env': {}, global: 'window' }, build: { rollupOptions: { plugins: [ require('rollup-plugin-node-polyfills')({ include: ['node_modules/**'], exclude: [], sourceMap: false }) ] } } });
3. 调整main.tsx代码
移除直接赋值window.process的代码,保留必要的全局挂载:
import { Buffer } from 'buffer'; window.global = window; window.Buffer = Buffer;
原理说明
- Vite默认会将Node.js核心模块标记为外部依赖,避免在浏览器代码中引入不兼容的API,因此不能直接导入完整
process模块,需使用其浏览器兼容版本process/browser - 通过
rollup-plugin-node-polyfills注入polyfill,确保wagmi及相关连接器能访问到所需的Node.js环境API - 定义
process.env为空对象,可避免依赖库访问process.versions这类浏览器中不存在的属性
内容的提问来源于stack exchange,提问作者theanh098
相关产品推荐
相关产品推荐

