Next.js static generation with dynamic imports

Viewed 225

I have a Template component which builds a page based on a json structure. The json contains multiple objects including keys, which then define what component is to be used.

Like this:

const componentList: Record<string, any> = {
    BlockCards: dynamic<Data.BlockCards>(() =>
        import("../molecule/BlockCards").then(module => module.BlockCards)
    ),
    BlockNews: dynamic<Data.BlockNews>(() =>
        import("../molecule/BlockNews").then(module => module.BlockNews)
    ),
    PageHeader: dynamic<Data.PageHeader>(() =>
        import("../atom/PageHeader").then(module => module.PageHeader)
    ),
};

interface TemplateProps {
    data: Data.Main;
}

export const Template: React.FC<TemplateProps> = ({ data }) => {
    return (
        <React.Fragment>
            {data.content.map((item, index) => {
                const Component = componentList[item.component.type];

                if (!Component) return null;

                return (
                    <Block key={index}>
                        <Component {...item.component} {...props} />
                    </Block>
                );
            })}
        </React.Fragment>
    );
};

This works, but the components are lazy loaded on the client's side. I want the rendering to happen on build, just like with getStaticProps. Importing my components without using dynamic works and the components will be prerendered thanks to next's static optimization. But since this one Template components imports multiple components that might not be used by some pages, I need the components to be only imported if used - how can I do so?

0 Answers
Related