javascriptwebpackcommentsreact-lazy-load

Is it possible to inject a variable value into a javascript comment?


TL;DR: is it possible to inject constant variables (that won't change during runtime) in comments

I've come across a very unique situation where I need my comments to have a specific value in them.

I'm code splitting in React and the way to name chunks in react is to add comment next to the import like this:

const MyComponent = lazy(() =>
  import('./MyComponent' /* webpackChunkName: "MyComponent" */)
)

This gives my lazy loaded chunks readable names over generated id names.

There's a section in my codebase where I generate lazy loaded routes for my components based on my folder structure, but I've hit a wall where I can't set my chunk name to a variable set by a function.

Here's my function:

function generateLink(label: string) {
  const path = label.replaceAll(' ', '');
  return {
    Element: lazy(
      () => import(`./pages/${path}`, /* webpackChunkName: "{{this should be path}}" */)
    ),
    label,
    path
  };

}

Is there anyway for me to inject the path variable into that comment?

An extra side note, this generateLink function is not run during runtime, the links are static.


Solution

  • Unfortunately there's no simple method for injecting variables into your comments. However, there is a webpack solution to your specific problem, just use Magic Comments

    Updating your generateLink function to the following should resolve your problem.

    function generateLink(label: string) {
      const path = label.replaceAll(' ', '');
      return {
        Element: lazy(
          () => import(`./pages/${path}`, /* webpackChunkName: "[request]" */)
        ),
        label,
        path
      };
    }
    

    Now if your path is HomePage, your chunk name will resolve to /HomePage.[chunkId].js

    Just make sure that all your file names are unique, otherwise webpack will suffix a number to your chunks for non-unique file names.

    E.g. if you have 2 file names of HomePage.jsx, then you will end up with /HomePage0.[chunkId].js and /HomePage2.[chunkId].js