gpt4 book ai didi

javascript - NextJS 项目中使用的 ReactJS 库表示不是构造函数

转载 作者:行者123 更新时间:2023-12-05 02:34:35 25 4
gpt4 key购买 nike

我已经构建了一个 ReactJS 库并将其发布到 NPM,并且在标准 ReactJS 项目中运行良好,但我现在有一个 NextJS,我正在尝试将它添加到那里,我希望它能正常工作,因为 NextJS 是一个框架ReactJS 的顶部具有一些附加功能。

在 app.js 中我有以下内容:

import dynamic from 'next/dynamic'
import {useEffect} from "react";

function MyApp({ Component, pageProps }) {

const {CrashCatch, CrashCatchProvider} = dynamic(import('crashcatchlib-reactjs'), { ssr: false })

let crash_catch = new CrashCatch();

crash_catch.initialiseCrashCatch("12978650", "d7kqcewvshoyxbp564f8tm0zl", "1.0.1");

return (
....
)
}

运行时我得到 TypeError: CrashCatch is not a constructor

我曾尝试不使用动态导入并执行标准导入,如 import {CrashCatch, CrashCatchProvider} from "crashcatchlib-reactjs"; 但随后我收到错误 SyntaxError: Cannot use模块外的导入语句]

reactjs 库的源代码是开源的,因此可以在 GitHub 上获得 https://github.com/Crash-Catch/CrashCatchLib-ReactJS . index.js 有 CrashCatch 类,它有构造函数,所以不确定为什么 NextJS 以不同的方式对待它。

最佳答案

NextJS 在服务器端执行代码,因此您的库也应该与 Node.js 兼容。 CommonJS 似乎不支持导入,这是 Node 使用的默认模块格式。但是,您可以指定您的库应被视为 ES 模块以支持导入语句,如文档中所述 https://nodejs.org/api/esm.html#enabling

Node.js treats JavaScript code as CommonJS modules by default. Authors can tell Node.js to treat JavaScript code as ECMAScript modules via the .mjs file extension, the package.json "type" field, or the --input-type flag. See Modules: Packages for more details.

您可以尝试在 package.json 中将 type 属性设置为 module

关于javascript - NextJS 项目中使用的 ReactJS 库表示不是构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70746210/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com