reactjs React - Google电子表格导入失败

ozxc1zmp  于 2023-02-18  发布在  React
关注(0)|答案(1)|浏览(167)

尝试在我的React应用程序中执行import { GoogleSpreadsheet } from 'google-spreadsheet',但出现此严重错误

Uncaught ReferenceError: process is not defined
    at loadProxy (gaxios.ts:66:5)
    at node_modules/gaxios/build/src/gaxios.js (gaxios.ts:75:1)
    at __require (chunk-RSJERJUL.js?v=0db569af:3:50)
    at node_modules/gaxios/build/src/index.js (index.ts:15:1)
    at __require (chunk-RSJERJUL.js?v=0db569af:3:50)
    at node_modules/gcp-metadata/build/src/index.js (index.ts:8:1)
    at __require (chunk-RSJERJUL.js?v=0db569af:3:50)
    at node_modules/google-auth-library/build/src/auth/googleauth.js (googleauth.js:19:21)
    at __require (chunk-RSJERJUL.js?v=0db569af:3:50)
    at node_modules/google-auth-library/build/src/index.js (index.js:17:22)

下面是我当前应用程序结构的截图,我已经开始使用Vite(这可能就是为什么这不起作用?)

包.json

{
  "name": "tinder-triage",
  "private": true,
  "version": "0.0.0",
  "type": "module",
  "scripts": {
    "dev": "vite",
    "build": "vite build",
    "preview": "vite preview"
  },
  "dependencies": {
    "google-spreadsheet": "^3.3.0",
    "react": "^18.2.0",
    "react-dom": "^18.2.0"
  },
  "devDependencies": {
    "@types/react": "^18.0.27",
    "@types/react-dom": "^18.0.10",
    "@vitejs/plugin-react": "^3.1.0",
    "vite": "^4.1.0"
  }
}

维生素配置js

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [react()],
})
slhcrj9b

slhcrj9b1#

似乎与google-spreadsheet软件包有关,该软件包设计用于Node.js而不是浏览器环境,google-spreadsheet软件包内部使用gaxios软件包,而gaxios软件包又依赖于进程变量。
要解决这个问题,你可以在React应用中使用googleapis软件包而不是google-spreadsheet。googleapis软件包设计为在Node.js和浏览器环境中工作,它提供了一个类似的界面来访问Google Sheets作为google-spreadsheet。下面是你安装googleapis软件包的方法:

npm install googleapis

下面是一个如何使用googleapis包访问Google工作表的示例:

import { google } from 'googleapis';

// Create a new instance of the Sheets API client
const sheets = google.sheets({ version: 'v4' });

// Authenticate with Google using OAuth 2.0 credentials
const auth = new google.auth.OAuth2(
  YOUR_CLIENT_ID,
  YOUR_CLIENT_SECRET,
  YOUR_REDIRECT_URL
);
auth.setCredentials({
  access_token: YOUR_ACCESS_TOKEN,
  refresh_token: YOUR_REFRESH_TOKEN
});

// Use the Sheets API client to read data from a Google Sheet
const res = await 
sheets.spreadsheets.values.get({
  auth: auth,
  spreadsheetId: YOUR_SPREADSHEET_ID,
  range: 'Sheet1!A1:B2'
});

console.log(res.data.values);

这段代码使用OAuth 2.0凭据向Google进行身份验证,然后使用googleapis包从Google工作表读取数据。您需要使用自己的OAuth 2.0凭据、访问令牌、刷新令牌和Google工作表ID替换占位符。

相关问题