How to dynamic import in nextjs correctly?

Viewed 27

I am trying to use nextjs dynamic import. I am using nextjs "^12.3.0" and typescript with module path aliases.

Here is HomeIcon component.

export const HomeIcon: FunctionComponent<IconProps> = ({ onClick }) => {
  return (
    <svg
      xmlns="http://www.w3.org/2000/svg"
      fill="none"
      onClick={onClick}
      viewBox="0 0 24 24"
      strokeWidth={1.5}
      stroke="currentColor"
      className="w-6 h-6"
    >
      <path
        strokeLinecap="round"
        strokeLinejoin="round"
        d="M2.25 12l8.954-8.955c.44-.439 1.152-.439 1.591 0L21.75 12M4.5 9.75v10.125c0 .621.504 1.125 1.125 1.125H9.75v-4.875c0-.621.504-1.125 1.125-1.125h2.25c.621 0 1.125.504 1.125 1.125V21h4.125c.621 0 1.125-.504 1.125-1.125V9.75M8.25 21h8.25"
      />
    </svg>
  );
};

So, my component imports looks like so..

import { HomeIcon } from '@/components/Icons/HomeIcon';

Usage:

<HomeIcon />

With Nextjs I am trying to import dynamically

import dynamic from 'next/dynamic';

const DynamicHomeIcon =dynamic(() =>  import '@/components/Icons/HomeIcon');

Usage:

<DynamicHomeIcon />

I get the following error with TS. How do I fix that?

error

1 Answers

For a named export like your case, you need to return it from the Promise. So your dynamic import should look like this:

const DynamicHomeIcon = dynamic(() =>  import ('@/components/Icons/HomeIcon').then(mod => mod.HomeIcon));

For a reference, its mentioned here in the doc

Related