Can you feed a Webpack magic comment with a specified variable?

Viewed 211

A colleague and I have been trying to write a function for dynamically importing components into our Vue app. We're bundling our code with Webpack 5. At the moment our function looks like this:

const dynamicImport = (pathName, request, resolve, canTryAgain) => {
    import(/* webpackChunkName: '[request]' */ `${pathName}/${request}`)
        .then(component => resolve(component.default))
        .catch(() => {
            if (canTryAgain) {
                dynamicImport(pathName, request, resolve, false);
            } else {
                location.reload();
            }
        });
};

Our hope was that the [request] placeholder in the magic comment would take our request parameter, and name the bundle resulting from this function after whatever we feed that parameter. However, Webpack just takes the entire line that we feed into the import statement ${pathName}/${request} and uses it for naming our bundles. This results in really long and not very elegant file names to use in our frontend. Any idea of how to still feed the import statement two variables/parameters, and have the magic comment only use one of them for naming the bundle?

1 Answers

I don't have the exact solution, but I can point you in some sort of directly. This would likely be managed on the babel-plugin side of things.

Use the loadable-components library as an example. There is the main component library (which would include code similar to what you wrote above), then there is the webpack side of things where transformations occur in a babel plugin.

Loadable Components:

https://loadable-components.com/

Loadable Components Repo:

https://github.com/gregberge/loadable-components/

Babel Chunk Name Functions:

https://github.com/gregberge/loadable-components/blob/main/packages/babel-plugin/src/properties/chunkName.js

Related