0

I'm building a NextJS app which fetches data from a strapi CMS at build time. Strapi allows to organize content using components and I would like to map strapi components to the ones of my Next project in order to build each web page according to the data fetched from strapi.

I would like, though, to keep my code clean and export a variable named strapiComponentId from each module that also exports a component (as a default export) in order to construct my component mapping at build time.

I was able to achieve this by using webpack's require.context, inspecting all the modules inside the components directory storing in an object all the ones that export a strapiComponentId variable. The code is following:

const req = require.context("@/components", false, /components.*\.js$/);

const mapping = req.keys().reduce((acc, current) => {
  const componentModule = req(current);
  if (componentModule.strapiComponentId != undefined) {
    acc[componentModule.strapiComponentId] = componentModule.default;
  }
  return acc;
}, {});

This way I have a map that, given a strapi component id (which is part of the strapi response), returns the related component. The code does not handle errors but works for testing purposes.

In order for the req(current) function to return an object instead of a promise I had to set experimental: { esmExternals: false } in next.config.js, as stated here.

My question is, then, the following:

Is there better solution in order to achieve the same result (maybe using next/dynamic feature)? If not, which are the side effects caused by disabling esmExternals?

Thank you for your time.

canta2899
  • 394
  • 1
  • 7

0 Answers0