Home > Software engineering >  Does Webpack code split within a switch statement?
Does Webpack code split within a switch statement?

Time:10-16

Does Webpack code split unused code in a switch statement?

I have an Icon component with a switch statement to choose the selected icon. This is a simplified version of the code, in reality it will be quite a large file:

switch (name) {
    case 'tick':
        return (
            <svg>
                <!-- more SVG code -->
            </svg>
        );
    case 'close':
        return (
            <svg>
                <!-- more SVG code -->
            </svg>
        );

If I use this component once on a page with the tick condition, will the code for close also be loaded?

CodePudding user response:

Nope. It will not. The only code elimination that Webpack can perform is what it can target via tree shaking. The tree shaking works at a module level and eliminate unused exports and its dependencies provided the module is side-effects free. What you are wishing here is aggressive elimination at branch level. So far, nothing can perform such optimization. You can explore closure compiler but I am still skeptical.

To design an icons system, I would typically have a icon component with outer <svg> tag and inside which I will use icon fragments which are defined in some dictionary (map or traditional object). That solves your readability problem with large switch case.

  • Related