What is the difference between hardcoding a string and using a variable containing a string when referencing an object? Affects Webpack tree shaking

Viewed 50

It feels like these forEach loops should be equivalent but somehow the variable causes the Webpack tree shaking (I assume) to be much less aggressive, and my project is structured in a way where I need it to be aggressive. Code is stripped down to show just the issue mentioned. For context I'm building a boilerplate that allows the user/client to use flexible drag and drop modules that represent React Components.

// AllModules = Object of React Components
moduleNames = ['ModuleName'];

moduleNames.forEach((name) => {
    const Module = AllModules[name]; // Webpack compiles assets for every component in AllModules
});

moduleNames.forEach((name) => {
    const Module = AllModules['ModuleName']; // Webpack compiles only the assets for ModuleName
});

I'd rather not mess with Webpack settings if possible, that always seems to open up a can of worms, but I will if necessary. Is there any way to use the variable that behaves exactly as the hardcoded string does?

0 Answers
Related