找不到模块:无法解析“child_process” - google-spreadsheet

Die*_*wa 7 javascript google-sheets reactjs google-sheets-api next.js

我正在尝试将表单数据保存到 Next.js 中的电子表格中,但我不断收到此错误,该错误在导入后立即出现google-spreadsheet

错误

在此输入图像描述

./node_modules/google-spreadsheet/node_modules/google-auth-library/build/src/auth/googleauth.js:17:0 找不到模块:无法解析“child_process”

波纹管是我所拥有的导致错误的原因。

// The error appears when I do this import
import { GoogleSpreadsheet } from "google-spreadsheet";

const SPREADSHEET_ID = process.env.NEXT_PUBLIC_SPREADSHEET_ID;
const SHEET_ID = process.env.NEXT_PUBLIC_SHEET_ID;
const CLIENT_EMAIL = process.env.NEXT_PUBLIC_GOOGLE_CLIENT_EMAIL;
const PRIVATE_KEY = process.env.NEXT_PUBLIC_GOOGLE_SERVICE_PRIVATE_KEY;

const doc = new GoogleSpreadsheet(SPREADSHEET_ID);

const appendSpreadsheet = async (row) => {
    try {
      await doc.useServiceAccountAuth({
        client_email: CLIENT_EMAIL,
        private_key: PRIVATE_KEY,
      });
      // loads document properties and worksheets
      await doc.loadInfo();

      const sheet = doc.sheetsById[SHEET_ID];
      const result = await sheet.addRow(row);
      return result;
    } catch (e) {
      console.error("Error: ", e);
    }
};
Run Code Online (Sandbox Code Playgroud)

小智 9

我只是解决它。

请在根目录中创建 next.config.js 文件。并在下面填写。

module.exports = {
  webpack: config => {
    config.node = {
      fs: 'empty',
      child_process: 'empty',
      net: 'empty',
      dns: 'empty',
      tls: 'empty',
    };
    return config;
  },
};
Run Code Online (Sandbox Code Playgroud)

呼啦!


cam*_*ser 8

我在使用 nextjs 12 时遇到了这个问题。以下是为我解决的问题:

我的代码:

const doc = new GoogleSpreadsheet(SPREADSHEET_ID);
await doc.useServiceAccountAuth({
  client_email: process.env.GOOGLE_SERVICE_ACCOUNT_EMAIL,
  private_key: process.env.GOOGLE_PRIVATE_KEY,
});
    
await doc.loadInfo(); 
console.log('title', doc.title);
Run Code Online (Sandbox Code Playgroud)

我的 next.config.js:

const nextConfig = {
  reactStrictMode: true,
  webpack: (config, { isServer }) => {
    if (!isServer) {
      config.resolve.fallback.fs = false
      config.resolve.fallback.tls = false
      config.resolve.fallback.net = false
      config.resolve.fallback.child_process = false
    }

    return config
  },      
}

module.exports = nextConfig;
Run Code Online (Sandbox Code Playgroud)

从这里获取灵感/修复