简体   繁体   English

在webpack中更好的TreeShaking的正确方法是什么?

[英]What is the right way for better TreeShaking in webpack?

I was wondering, which one of the following two options is the right way for better Tree Shaking in webpack : 我想知道,以下两个选项中的哪一个是在webpack中更好的Tree Shaking的正确方法:

import { someFeature } from 'someModule'  // Option 1
import { isEmpty } from 'lodash' // Example 1

Or, 要么,

import someFeature from 'someModule/someFeature' // Option 2
import isEmpty from 'lodash/isEmpty' // Example 2

If I understand your question, I think you are asking for the benefits of named exports over default exports for better tree shaking or reducing the bundle size. 如果我理解你的问题,我认为你要求命名导出优于默认导出的好处,以更好地树摇或减少捆绑大小。

For better tree shaking, it is advised to use named export over default exports. 为了更好地树摇动,建议使用命名导出而不是默认导出。 According to this article , 根据这篇文章

Sometimes you can be tempted to export one huge object with many properties as default export. 有时您可能想要将具有许多属性的一个巨大对象导出为默认导出。 This is an anti-pattern and prohibits proper tree shaking: 这是一种反模式,禁止树木正常摇动:

So instead of using default export as example 1 use named export as example 2. 因此,不使用默认导出作为示例1,而是使用命名导出作为示例2。

Example 1 例1

// This is default export. Do not use it for better tree shaking
// export.js
 export default {
   propertyA: "A",
   propertyB: "B",
 }
// import.js
import export from './exports';

Example 2 例2

// This is name export. Use it for better tree shaking
// export.js
 export const propertyA = "A";
 export const propertyB = "B";
// import.js
import { propertyA } from './exports';

So in the first example it will export both propertyA and propertyB while in the second it will only export propertyA which will reduce the bundle size. 所以在第一个例子中它将导出propertyApropertyB而在第二个例子中它只会导出propertyA ,这将减少bundle的大小。

No matter if you use option one or two, it will not be possible to "tree shake" unused things from your "someFeature" if that is one huge object or class with many properties and you are using only some of those properties. 无论你使用选项一还是二,如果那是一个巨大的对象或具有许多属性的类而你只使用其中一些属性,那么就不可能从“someFeature”中“树”掉未使用的东西。 So the best option would be to chunk your "someFeature" into smaller pieces and export those smaller pieces as named exports. 因此,最好的选择是将“someFeature”分成较小的部分,并将这些较小的部分导出为命名导出。

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

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