这是一个称为桶文件的概念。这些文件使导入类更加方便。这不仅仅是 Angular 的一个概念。使用它们似乎是 TypeScript 的最佳实践。
当您有一个较小的项目时,您可能看不到创建这些文件的太多好处,但是当您与多个团队成员一起处理较大的项目时,它们会非常有用。以下是我所知道的一些优点/缺点。
优点:模块内部结构所需的知识较少
当组件需要引用某些内容时,它不必知道类等所在的确切文件。当您不将这些内容存储在模块内时,模块外部的所有其他文件都将需要确切地知道哪个文件(包括子路径)包含该项目。如果您将物品放入单个模块桶中,您只需知道它来自哪个模块即可。这还为您带来了重构模块的好处,不需要您确保在文件移动时更新路径(您的工具可能会或可能不会帮助解决此问题)。
// without barrel files
import { Class1 } from 'app/shared/module1/subpath1/subpath2/class1.service';
// using barrel files
import { Class1 } from 'app/shared/module1';
优点:显式导出外部模块
另一个好处是,一个模块可能包含一堆类、接口等,这些类、接口等实际上只在该模块内使用。通过为模块创建桶文件,您可以让其他开发人员知道在模块外部使用的内容。此外,您让他们确切地知道要使用哪些项目,因此他们不需要到处寻找他们需要的界面(同样,您的工具可能会或可能不会对此提供帮助)。
// export these items from module as others need to have references to these
export { ExampleModule } from './example.module';
export { ExampleService } from './example.service';
export { ExampleInterface } from './example.model';
// these also exist in module but others don't need to know about them
// export { ExampleComponent } from './example.component';
// export { Example2Service } from './example2.service';
// export { ExampleInterface2 } from './example.model';
优点:更清洁的进口
我要提到的最后一个好处是它有助于清理您的进口。它不仅可以更清楚地显示哪些项目来自哪些模块,还有助于使from
导入的部分要短得多,因为您不需要遍历子目录等。请注意,最佳实践似乎是将桶文件index.ts
位于文件夹中,因为当给定要从中导入的文件夹时,TypeScript 编译器将默认查找该文件。
// without barrel files (hopefully they would be not randomly ordered to make it even harder...)
import { Class1 } from 'app/shared/module1/subpath1/subpath2/class1.service';
import { Class2 } from 'app/shared/module1/subpath1/class2.component';
import { Interface1 } from 'app/shared/module1/module1.model';
import { Class3} from 'app/shared/module2/subpath3/class3.service';
import { Interface2 } from 'app/shared/module2/module2.model';
// using barrel files
import { Class1, Class2, Interface1 } from 'app/shared/module1';
import { Class3, Interface2 } from 'app/shared/module2';
缺点:附加文件
在尝试识别缺点时,我唯一能想到的是您正在为每个模块创建另一个文件(或者可能是子文件夹,具体取决于您想要如何执行此操作)。据我所知,它没有运行时或编译时效果。