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

标签 javascript reactjs next.js server-side-rendering

我已经构建了一个 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/

相关文章:

typescript - 类型 'target' 上不存在属性 'KeyboardEventHandler<HTMLInputElement>'

javascript - 如何使用 web3modal 获取已连接钱包的地址?

javascript - 增加对变量范围和声明的理解

javascript - 如何使用 javascript 作为事件文本显示 <img> 标签

javascript - 将 POST 数据发送到 PHP 脚本 - jQuery、AJAX 和 PHP

reactjs - 为什么我在启动 React 应用程序时收到错误 "[Error: std::bad_alloc]"?

reactjs - 类型错误 : Cannot read properties of null (reading 'useMemo' )

reactjs - ButtonGroup 内的按钮组件

javascript - Appcelerator TableView > 行 > 文本字段 > 值

javascript - 从本地 json 文件创建动态路由 nextjs 13