React lazy import doesn't work when using inside for loop

Viewed 407

I want to create folder-based router management and splitting the whole pages into chunk files by using webpackChunkName. if I declared my whole routes into a static array, chunk splitting and lazy loading work fine. However, when I use React.lazy import inside a for loop, it doesn't work at all. It wont split any chunk file based on each route.

So here is my declarations:

This works like a charm:

links: [
      {
        id: "about",
        path: "/about",
        component: lazy(() =>
          import(/* webpackChunkName: "About" */ "@/views/About")
        ),
        icon: faExclamationCircle,
      },
      {
        id: "guide",
        path: "/guide",
        component: lazy(() =>
          import(/* webpackChunkName: "Guide" */ "@/views/Guide")
        ),
        icon: faBookReader,
      },
    ],

When I try to dynamic import inside a for loop, it doesn't work at all...

  sections: result[0].pages.map((i) => {
      // It throws an error if doesn't have a config file
      const config = require(`@/views/sections/${i.section}/config.js`).default;
      return {
        id: i.section,
        icon: config.icon,
        groups: config.group,
        pages: i.pages.map((x, k) => {
          if (x.section === "index.js")
            return {
              id: i.section,
              path: "/" + i.section,
              component: lazy(() =>
                /* webpackChunkName: "someModule",  */
                import(`@/views/sections/${i.section}/index.js`)
              ),
            };

          return {
            id: getCleanPath(x.section),
            path:
              k === 0
                ? `/${i.section}`
                : getCleanFullPath(i.section, x.section),
            component: lazy(() =>
              import(
                /* webpackChunkName: "someModule" */
                `@/views/sections/${i.section}/${x.section}`
              )
            ),
          };
        }),
      };
    }),
1 Answers

Ups, I used require.context for getting all folders inside the src folder, so I have to load it 'lazy'. That's why webpack won't split chunk files.

// Before
require.context("../views/sections", true, /^(?!.*config\.js$).*\.(js)$/)
// After
require.context("../views/sections", true, /^(?!.*config\.js$).*\.(js)$/, "lazy")
Related