简体   繁体   English

TypeScript 类和 Webpack

[英]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.假设我有一个具有 10 种方法的 typescript class 并且该文件导出 class 的新实例作为其默认导出。 Then I have another file, like a React functional component, that import this class and call one method on the class.然后我有另一个文件,比如 React 功能组件,它导入这个 class 并在 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? Webpack/Babel 可以仅提取所使用方法的代码,还是包含整个 class 并且我会有一堆未使用的代码?

Is it better to avoid classes and export each function instead?避免上课并导出每个 function 会更好吗?

My goal is to make the exported bundles smaller and also have Lighthouse complain less about unused JavaScript.我的目标是使导出的捆绑包更小,并且让 Lighthouse 更少抱怨未使用的 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 .大多数摇树工具(包括 Webpack)通过分析 ES6 的importexport的树来摇树未使用的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.用Webpack摇树时,如果在某处使用了myFunc1 myFunc2不能摇树。

But here, either function could be tree shaken if not used:但是在这里,如果不使用 function 可能会被摇树:

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.在这种情况下,摇树(使用 Webpack)最好使用组合在一个文件中的函数,而不是 class。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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