I have built a ReactJS library and published it to NPM and works fine in a standard ReactJS project, but I now have a NextJS and I am trying to add it there, I expected it would just work as NextJS is a framework on top of ReactJS with some additional functionality.
In the app.js I have the following:
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 (
....
)
}
When running this I get TypeError: CrashCatch is not a constructor
I have tried not using a dynamic import and doing a standard import as import {CrashCatch, CrashCatchProvider} from "crashcatchlib-reactjs";
but then I get the error SyntaxError: Cannot use import statement outside a module
]
The source code for the reactjs library is open source so it’s available on GitHub at https://github.com/Crash-Catch/CrashCatchLib-ReactJS. The index.js has the class CrashCatch which has the constructor so not sure why NextJS is treating it differently.
NextJS executes code on the server-side, so your library should also be compatible with Node. It seems import is not supported in CommonJS, which is the default module format used by Node. However, you can specify that your library should be treated as an ES Module to support import statements as described in the documentation https://nodejs.org/api/esm.html#enabling
You could try setting the
type
property tomodule
in your package.json