React项目导入GoogleSpreadsheet报错:process is not defined
解决Vite React项目中使用google-spreadsheet出现process is not defined的问题
问题原因
Vite默认不会像Webpack那样在浏览器环境中注入process全局变量,而google-spreadsheet依赖的底层库(如gaxios、gcp-metadata)会尝试访问process.env,导致报错。另外,该库本身为Node.js环境设计,依赖多个Node.js内置模块(如http、https),浏览器环境默认不支持这些模块。
解决方案
步骤1:注入process环境变量
修改vite.config.js,添加define配置注入process.env:
import { defineConfig } from 'vite' import react from '@vitejs/plugin-react' export default defineConfig({ plugins: [react()], define: { 'process.env': {} // 注入空对象避免未定义报错 } })
步骤2:补充Node.js模块polyfill
安装vite-plugin-node-polyfills插件,填补浏览器缺失的Node.js内置模块:
npm install vite-plugin-node-polyfills --save-dev
修改vite.config.js引入并启用插件:
import { defineConfig } from 'vite' import react from '@vitejs/plugin-react' import { nodePolyfills } from 'vite-plugin-node-polyfills' export default defineConfig({ plugins: [ react(), nodePolyfills({ include: ['http', 'https', 'url', 'stream', 'crypto'], globals: { process: true // 全局注入process对象 } }) ] })
关键安全提醒
绝对不能在前端代码中直接使用Google服务账号密钥,这会导致密钥泄露,任何人都可随意访问你的Google Sheets数据。正确做法是:
- 搭建Node.js后端服务,在后端用
google-spreadsheet处理表格读写 - 前端通过API接口与后端通信,间接操作表格数据
验证修改
重启Vite开发服务器,重新导入GoogleSpreadsheet,此时process is not defined的报错应消失。若仍有其他Node模块相关报错,可在nodePolyfills的include数组中添加对应模块。
内容的提问来源于stack exchange,提问作者giaggi
相关产品推荐
相关产品推荐

