Next.js Discord

Discord Forum

Next dynamic behaviour error.

Unanswered
American Crocodile posted this in #help-forum
Open in Discord
American CrocodileOP
I'm trying to do a dynamic component loading, but can't simply understand why the behaviour change using same code, but passing an external string instead of direct one.

So, this code works:

import { LOCALES } from '@/constants'
import Link from 'next-intl/link'
import dynamic from 'next/dynamic'

const import_strings = LOCALES.map((locale) => ({
    flag_import: `country-flag-icons/react/3x2/${locale.flag}`,
    i18n: locale.i18n,
}))

const FlagComponents = import_strings.map((locale) => ({
    ...locale,
    Component: dynamic(() => import(`country-flag-icons/react/3x2/GB`), { ssr: false }),
}))

function LanguageSwitcher() {
    return (
        <>
            {FlagComponents.map(({ i18n, Component }) => (
                <Link href='/' locale={i18n} key={i18n}>
                    <Component className='flags' />
                </Link>
            ))}
        </>
}

But if try to change the FlagComponents effectively to use the full string like this:
const FlagComponents = import_strings.map((locale) => ({
    ...locale,
    Component: dynamic(() => import(locale.flag_import), { ssr: false }),
}))


I got the attached image error:
Error: Cannot find module 'country-flag-icons/react/3x2/GB'

So what's different?

Btw, I'm using Next.js 14.0.1 on a M2 Mac.

The LOCALES format imported above is like this:
export const LOCALES = [
    { i18n: 'en', flag: 'GB' },
    { i18n: 'ja', flag: 'JP' },
    { i18n: 'vi', flag: 'BR' },
    { i18n: 'zh', flag: 'ZH' },
    { i18n: 'pt-BR', flag: 'BR' },
]

1 Reply

Argentine hake
You can't use a variable for an import. See https://nextjs.org/docs/pages/building-your-application/optimizing/lazy-loading#basic-usage

Good to know: In import('path/to/component'), the path must be explicitly written. It can't be a template string nor a variable...