简体   繁体   中英

TypeScript classes and Webpack

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.

Most tree shaking tools (including Webpack) work by analysing the tree of ES6 import s and export s 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM