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

时间:2021-03-20 10:12:19

标签: javascript reactjs google-sheets next.js google-sheets-api

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

错误

enter image description here

<块引用>

./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);
    }
};

3 个答案:

答案 0 :(得分:3)

我只是解决它。

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

module.exports = {
  webpack: config => {
    config.node = {
      fs: 'empty',
      child_process: 'empty',
      net: 'empty',
      dns: 'empty',
      tls: 'empty',
    };
    return config;
  },
};

万岁!

答案 1 :(得分:0)

尝试将导入语句更改为:

const { GoogleSpreadsheet } = require('google-spreadsheet');

来源:https://www.npmjs.com/package/google-spreadsheet

答案 2 :(得分:0)

该库尚不支持 ES6 功能

如果您查看模块导出,您会发现如下内容:

module.exports = {
  GoogleSpreadsheet,
  GoogleSpreadsheetWorksheet,
  GoogleSpreadsheetRow,

  GoogleSpreadsheetFormulaError,
};

https://github.com/theoephraim/node-google-spreadsheet/blob/master/index.js

将导入语句更改为 commonjs 模块,如下所示:

const { GoogleSpreadsheet } = require('google-spreadsheet');