我正在尝试将表单数据保存到 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);
}
};
我刚刚解决了。
请在根目录中创建 next.config.js 文件。 并在下面填写。
module.exports = {
webpack: config => {
config.node = {
fs: 'empty',
child_process: 'empty',
net: 'empty',
dns: 'empty',
tls: 'empty',
};
return config;
},
};
呼啦!
我在使用 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);
我的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;
从这里
获取灵感/修复尝试将导入语句更改为:
const { GoogleSpreadsheet } = require('google-spreadsheet');
原因是你需要的库使用了一些nodejs原生模块,如
path
、fs
或child_process
。
作为构建过程的一部分,nextjs 将为您的客户端和服务器分别创建 js 包。问题是您的客户端构建无法解析这些 Nodejs 模块。作为解决方法,您可以告诉 nextjs 仅在客户端构建时忽略这些模块。
next.config.js
const nextConfig = {
webpack: (config, { isServer }) => {
if (!isServer) {
config.resolve.fallback = {
fs: false,
path: false,
}
}
return config
}
}
module.exports = nextConfig;
@Camposer 的解决方案,指导了我。在您的 nextconfig.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;
该库尚不支持ES6功能
如果你查看模块导出,你会发现类似这样的东西:
module.exports = {
GoogleSpreadsheet,
GoogleSpreadsheetWorksheet,
GoogleSpreadsheetRow,
GoogleSpreadsheetFormulaError,
};
https://github.com/theoephraim/node-google-spreadsheet/blob/master/index.js
将导入语句更改为
commonjs
模块,如下所示:
const { GoogleSpreadsheet } = require('google-spreadsheet');