MastoJS + NextJS API 路由(无服务器):[TypeError]:类扩展值 #<Object> 不是构造函数或为空
2023-05-23
106
刚刚尝试使用 mastojs 和 nextjs api 路由。如果我通过 nodejs 从本地机器运行 mastojs 代码,它就可以正常工作:
import { login } from 'masto';
const masto = await login({
url: process.env.URL,
accessToken: process.env.TOKEN,
});
const status = await masto.v1.statuses.create({
status: 'Hello from #mastojs!',
visibility: 'public',
});
但是,在 nextjs api 路由中,它会出现错误。NextJS 中的代码如下所示:
import { NextResponse } from "next/server";
import { login } from 'masto';
export async function GET() {
const masto = await login({
url: process.env.URL,
accessToken: process.env.TOKEN,
});
return NextResponse.json({
hello: "world"
});
}
仅此一项就已经引发错误:
- error node_modules/.pnpm/ [email protected] /node_modules/masto/dist/index.cjs (3822:33) @ EventEmitter
- error Error [TypeError]: Class extends value # is not a constructor or null at eval (webpack-internal:///(sc_server)/./node_modules/.pnpm/ [email protected] /node_modules/masto/dist/index.cjs:3986:38) at Object.(sc_server)/./node_modules/.pnpm/ [email protected] /node_modules/masto/dist/index.cjs (/Users/xxx/.next/server/app/api/bots/mastodon/route.js:1982:1)
知道这可能是什么吗?mastojs 在无服务器函数中运行时是否存在问题?
1个回答
可能值得向
masto
维护者提交错误,因为该库在 Next.js 中无法开箱即用。
我设法通过以下步骤解决了所有编译问题:
- 安装可选依赖项:
npm i bufferutil encoding utf-8-validate
- 使用 patch-package 应用以下补丁:
patches/masto+5.11.3.patch
diff --git a/node_modules/masto/dist/index.cjs b/node_modules/masto/dist/index.cjs
index eb0fb04..7dcae64 100644
--- a/node_modules/masto/dist/index.cjs
+++ b/node_modules/masto/dist/index.cjs
@@ -4,7 +4,7 @@ var ponyfills = require('@mastojs/ponyfills');
var semver = require('semver');
var qs = require('qs');
var changeCase = require('change-case');
-var EventEmitter = require('eventemitter3');
+var EventEmitter = require('eventemitter3').EventEmitter;
var WebSocket = require('isomorphic-ws');
/**
希望这有帮助。
Igor Danchenko
2023-05-23