TypeScript classes and Webpack
Asked Answered
S

1

6

Let say I have a typescript class with 10 methods and that the file export a new instance of the class as its default export. Then I have another file, like a React functional component, that import this class and call one method on the class.

How will this be optimized? Can Webpack/Babel extract the code for just the method used, or will it include the whole class and I will have a bunch of unused code?

Is it better to avoid classes and export each function instead?

My goal is to make the exported bundles smaller and also have Lighthouse complain less about unused JavaScript.

Stanwood answered 20/12, 2020 at 14:59 Comment(5)
thought tree shaking of webpack etc is at module level, i.e. import/exportBehlke
Some context: github.com/rollup/rollup/issues/349. I wonder if when Lighhouse can detect unused class methods - why a bundler like Webpack or Rollup can't... Are you sure that this is even the case?Caprifig
given JS's dynamic feature, suppose we have a class with some methods that end with prime suffix, say, f_2, f_3 f_5 etc. And a function g(r) { if(r is prime && r< 100), then class_instance['f_' + r]() }; so engine has to do run time analysis in order to efficiently remove dead code?Behlke
madflow: No, I'm not sure, but still, if the bundle gets larger with no benefits it's good to choose a pattern which can remove that code. Or not write it in the first place. :)Stanwood
@JohanNordberg I would assert that, when optimizing for treeshakable code, avoiding classes is the pattern :SCaprifig
O
0

Most tree shaking tools (including Webpack) work by analysing the tree of ES6 imports and exports in order to tree shake unused exports.

Take the following example:

export class {
    myfunc1() { /* do stuff */ }
    myfunc2() { /* do stuff */ }
}

When tree shaking with Webpack, if myFunc2 is used somewhere, myFunc1 cannot be tree shaken even if it is not used.

But here, either function could be tree shaken if not used:

export myFunc1 = () => { /* Do stuff */}
export myFunc2 = () => { /* Do stuff */}

In this case it is better for tree shaking (with Webpack) to use functions grouped together in a file, rather than a class.

Oppilate answered 20/12, 2020 at 15:10 Comment(4)
It is not true that it cannot be tree-shaken. It is just very hard to implement. Your "advice" on when it is better to use classes etc ist not very useful.Caprifig
@Caprifig I didn't say it cannot be tree shaken. And in terms of tree shaking surely it is better to default to individual functions rather than classes as they work better with tree shaking tools and in many use cases have some other benefits too.Oppilate
"cannot be tree shaken"Caprifig
It depends on whether the code in under OP's controlBehlke

© 2022 - 2024 — McMap. All rights reserved.