简体   繁体   English

为 webpack 包大小导入文件的更好方法

[英]Better way to import files for webpack bundle size

hooks/index.js钩子/index.js

export { default as useDialog } from './useDialog'
export { default as useCurrencies } from './useCurrencies'
export { default as useUser } from './useUser'

Let's imagine that I have 3 files in hooks folder ( useDialog , useCurrencies , useUser ).假设我在hooks文件夹中有 3 个文件( useDialoguseCurrenciesuseUser )。 I want to make the correct imports from this folder.我想从此文件夹进行正确的导入。 Now I do imports like this:现在我做这样的导入:

import {useDialog} from 'hooks'

Is it correct way to import this file, or it is better to import it like import useDialog from 'hooks/useDialog' ?导入这个文件是正确的方法,还是像import useDialog from 'hooks/useDialog'那样导入更好? What is better for my bundle size?什么更适合我的捆绑包尺寸?

You can try yourself and compare the bundle sizes on production from before and after.您可以自己尝试并比较生产前后的捆绑包大小。 I'm gonna explain how to do it if anyone needs it.如果有人需要,我将解释如何做。

First do these steps with the code importing from the index: import {useDialog} from 'hooks'首先使用从索引导入的代码执行这些步骤: import {useDialog} from 'hooks'

yarn build
serve -s build

Open the local address (http://localhost:5000/) on incognito mode.隐身模式下打开本地地址(http://localhost:5000/)。 Then open Inspect -> Coverage.然后打开检查 -> 覆盖率。

At the bottom you can see the size.在底部你可以看到大小。 eg: 1.2MB of 2.1MB (55%) used so far 964kB unused例如:目前已使用 2.1MB 中的 1.2MB (55%) 未使用 964kB

Then change your code and import directly from the file: import useDialog from 'hooks/useDialog' , and repeat the build and check the size.然后更改您的代码并直接从文件中导入: import useDialog from 'hooks/useDialog' ,然后重复构建并检查大小。

Maybe if the files are too small you are not going to notice a difference, but you will if there are any big files or files that imports a big external library.如果文件太小,您可能不会注意到差异,但如果有任何大文件或导入大型外部库的文件,您会注意到。

I tried this comparison on my project and there was one file importing and using moment.我在我的项目中尝试了这种比较,并且有一个文件导入和使用时刻。 I was not even using this component, but the bundle size was increased because I was importing another component from the same index.我什至没有使用这个组件,但是由于我从同一个索引中导入了另一个组件,所以捆绑包的大小增加了。

Before I was always importing from a folder like 'hooks' , but from now on I will always import directly from the file 'hooks/useDialog' .之前我总是从'hooks'类的文件夹中导入,但从现在开始,我将始终直接从文件'hooks/useDialog'导入。

I'm just sharing my experience, Please, compare the bundles on your own projects!我只是分享我的经验,请在您自己的项目中比较捆绑包!

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

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