Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use dynamic import with a named export in Next.js?

I have this react component. It works just fine for me.

import { Widget } from 'rasa-webchat';

function CustomWidget(){
    return (
        <Widget
        initPayload={"payload"}
        socketPath={"/socket.io/"}
        customData={{"language": "en"}}
        />
    )
}
export default CustomWidget;

But when I try to use it on my next.js website it fails to work.

It gives me a window is not defined error.

I think I resolved this particular error by using the dynamic importer:

import dynamic from "next/dynamic";

const webchat = dynamic(
  () => {
    return import('rasa-webchat');
  },
  { ssr: false }
);

But now I can't figure out how to actually use the widget component from the package.

Am I allowed to import { Widget } from 'rasa-webchat' or is this just not compatible with next.js for some reason? If it's possible, how do I do it?

like image 336
Stephan Avatar asked Oct 20 '25 14:10

Stephan


1 Answers

The syntax for named exports is slightly different. You can use the widget with a dynamic import as follows:

import dynamic from 'next/dynamic';

const Widget = dynamic(
    () => import('rasa-webchat').then((mod) => mod.Widget),
    { ssr: false }
);

function CustomWidget(){
    return (
        <Widget
            initPayload={"payload"}
            socketPath={"/socket.io/"}
            customData={{"language": "en"}}
        />
    )
}

export default CustomWidget;

For further details check Next.js dynamic import documentation.

like image 102
juliomalves Avatar answered Oct 22 '25 03:10

juliomalves