AndreGeng / AndreGeng.github.io

blog repository
1 stars 0 forks source link

为什么您现在应该停止使用Barrel Files #67

Open AndreGeng opened 11 months ago

AndreGeng commented 11 months ago

原文链接 https://dev.to/tassiofront/barrel-files-and-why-you-should-stop-using-them-now-bc4 https://blog.vramana.com/posts/barrel_files_slow_build/

小决定也可能对应用程序产生重大影响。 当开发人员开始使用桶文件时,它们可能看起来是一种无害的模式,但事实并非如此。

什么是桶文件?

桶文件是一种简单的导出模式,允许开发人员从唯一的路径导入不同的文件。 让我们看一个例子:

// ./barrelFiles/used.ts
export const HEY = 'hey used';

// ./barrelFiles/notUsed.ts
export const HEY_NOT_USED = 'hey NOT used';
// ./barrelFiles/index.ts
export { HEY_NOT_USED } from './notUsed';
export { HEY } from './used';

/*
This is a barrel file, which will be used as a unique path to import any files into barrelFiles folder (such as ./used).
*/

使用它:

```ts
// ./Component.tsx

import { HEY } from './barrelFiles'; // instead of use './barrelFiles/used'

第一次接触时,看起来棒极了,不是吗? 他们是在开发经验方面,但是成本很高!

应用程序包中的 Barrel 文件成本是多少?

关于桶文件,您必须牢记一个关键问题:当我使用其中的某些内容时会导入什么? 它只导入我使用的内容吗? 让我们通过示例来看一下。 是的,让我们在桶文件中添加两个文件,并添加一些 console.log 来看看它们是如何工作的:

// now there are 4 files in barrelFiles folder

// ./barrelFiles/used.ts
export const HEY = 'hey used';
console.log('%c Im used xD', 'color: green;');

// ./barrelFiles/notUsed.ts
export const HEY_NOT_USED = 'hey NOT used';
console.log('%c WAIT! Im NOT used', 'color: red');

// ./barrelFiles/notUsed1.ts
export const HEY_NOT_USED_1 = 'hey NOT used 1';
console.log('%c WAIT! Im NOT used 1', 'color: red');

// ./barrelFiles/notUsed2.ts
export const HEY_NOT_USED_2 = 'hey NOT used 2';
console.log('%c WAIT! Im NOT used 2', 'color: red');

barrel file:

// ./barrelFiles/index.ts
export { HEY_NOT_USED } from './notUsed';
export { HEY_NOT_USED_2 } from './notUsed2';
export { HEY_NOT_USED_1 } from './notUsed1';
export { HEY } from './used';

好吧,回到问题上来,如果我导入HEY,我只导入 ./used 文件内容,这是预期的。 因此,让我们将其导入到我的个人项目中来完成此操作,您可以在其中找到更多类似这样的文章:

// ./Component.tsx

import { HEY } from './barrelFiles'; // I wanna use HEY, only

image

你有看到? 即使只使用了 HEY,它也会显示所有 console.log,这意味着所有文件都已导入。 现在,不从桶文件导入。

// ./Component.tsx

import { HEY } from './barrelFiles/used'; // I wanna use HEY, only

image

显示直接导入一个console.log。 您可能想知道:为什么我的项目中会有未使用的文件? 这是个好问题。 嗯,关于它的一些要点:

  1. 在这个例子中,文件很少,但是一个巨大的项目使用十几个桶文件怎么样? 可能会有未使用的文件。 如果您使用单一存储库,它可能具有用于许多应用程序的共享文件夹。 作为开发人员,创建避免团队成员(和您)做错事情的模式是您能做的最好的事情;
  2. 尽管 Vite 和 Webpack 等工具优化捆绑并避免使用重新导入块,但确保尽可能优化的更好方法是了解应用程序上的工作情况。

其它

这里还有一篇关于由Barrel File引入的包体积问题My Journey to 3x Faster Builds: Trimming Barrel File Imports