gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 10:56:09 24 4
gpt4 key购买 nike

我想知道,以下两个选项中的哪一个是在 webpack 中更好地 Tree Shaking 的正确方法:

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

或者,

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

最佳答案

如果我理解您的问题,我认为您是在询问命名导出相对于默认导出的好处,以便更好地进行 tree shaking 或减小包大小。

为了更好地摇树,建议使用命名导出而不是默认导出。根据这个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:

因此,在示例 1 中不使用默认导出,而在示例 2 中使用命名导出。

示例 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';

示例 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';

所以在第一个示例中它将导出 propertyApropertyB 而在第二个示例中它只会导出 propertyA 这将减少包大小。

关于javascript - 在 webpack 中更好的 TreeShaking 的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56816190/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com