3

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.

Barry Michael Doyle
  • 9,333
  • 30
  • 83
  • 143

2 Answers2

3

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

Barry Michael Doyle
  • 9,333
  • 30
  • 83
  • 143
kodamace
  • 475
  • 3
  • 9
2

This question has been answered before in https://stackoverflow.com/a/52345836/2188587

You can use a placeholder [request] and webpack will automatically use the resolved file name.

import(/* webpackChunkName: "[request]" */ `./pages/${path}`)

I checked the docs, it still exists.

Exception: It will use the file name, so if you have nested files and path variable can also use directories, you're probably out of luck.

Jakub Kotrs
  • 5,823
  • 1
  • 14
  • 30