How to generate dynamic import chunk name in webpack

╄→гoц情女王★ 提交于 2019-12-20 09:40:10

问题


I am dynamically calling an import statement in my typescript code, based on that webpack will create chunks like below:

you can see Webpack is automatically generating the file name as 1,2,3 respectively, the name is not a friendly name

I have tried a way to provide the chunk name through comment, but it's generating modulename1.bundle.js , modulename2.bundle.js

bootStrapApps(config) {

    config.apps.forEach(element => {

      registerApplication(
        // Name of our single-spa application
        element.name,
        // Our loading function
        () =>
          import(/* webpackChunkName: "modulename"*/  "../../" +
            config.rootfolder +
            "/" +
            element.name +
            "/" +

            "app.bootstrap.js"),
        // Our activity function
        () => true
      );
    });
    start();
}

Is there any way to specify the module name dynamically though this comment? I don't know this is specific to typescript or webpack.


回答1:


From webpack docs:

webpackChunkName: A name for the new chunk. Since webpack 2.6.0, the placeholders [index] and [request] are supported within the given string to an incremented number or the actual resolved filename respectively.

You can use [request] placeholder to set dynamic chunk name.
A basic example would be:

const cat = "Cat";
import(
  /* webpackChunkName: "[request]" */
  `./animals/${cat}`
);  

So the chunk name will be cat. But if you put the string Cat in the path, [request] will throw a warning during the build saying request was undefined.
So this will not work:

import(
  /* webpackChunkName: "[request]" */
  "./animals/Cat"
);  

Finally, your code would look something like this:

bootStrapApps(config) {
    config.apps.forEach((element) => {
      registerApplication(
        // Name of our single-spa application
        element.name,
        // Our loading function
        () =>
          import(/* webpackChunkName: "[request]" */ `../../${config.rootfolder}/${
            element.name
          }/app.bootstrap.js`),
        // Our activity function
        () => true
      );
    });
    start();
  }  

Look at this GitHub issue for more help. https://github.com/webpack/webpack/issues/4807

PS: Those comments are called webpack magic comments.



来源:https://stackoverflow.com/questions/52339114/how-to-generate-dynamic-import-chunk-name-in-webpack

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!