TypeScript classes and Webpack

Viewed 418

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.

1 Answers

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.

Related