关于 Angular 项目里的 index.ts
2023-09-14 09:02:57 时间
如下图所示:如果我需要在文件夹 A 里的某文件,访问文件夹 B 里的某服务,而文件夹 A 和 B 分别是两个不同 module 的实现,我需要在文件夹 A 的文件里,通过导入文件夹 B 里定义的 index 文件,来导入其暴露的服务,下面的例子里导入的是 BrowserService.
Jerryindex.ts 文件的内容:
如果 browser 文件下定义的是符合 Angular 命名规范的 index.ts 文件,则文件夹A里的导入语句,可以不显式包含 index.ts 这个文件名,简写成:
实际上,这些 index.ts 文件,称为 barrel file,在这个StackOverflow thread里有讨论。
桶是一种将多个模块的导出汇总到单个便利模块的方法。 桶本身是一个模块文件,用于重新导出其他模块的选定导出。
Imagine three modules in a heroes folder:
// heroes/hero.component.ts
export class HeroComponent {}
// heroes/hero.model.ts
export class Hero {}
// heroes/hero.service.ts
export class HeroService {}
如果没有桶,消费者将需要三个导入语句:
import { HeroComponent } from '../heroes/hero.component.ts';
import { Hero } from '../heroes/hero.model.ts';
import { HeroService } from '../heroes/hero.service.ts';
我们可以将一个桶添加到导出所有这些项目的 heros 文件夹(按惯例称为索引):
export * from './hero.model.ts'; // re-export all of its exports
export * from './hero.service.ts'; // re-export all of its exports
export { HeroComponent } from './hero.component.ts'; // re-export the named thing
现在消费者可以从桶中进口它需要的东西。
import { Hero, HeroService } from '../heroes'; // index is implied
更多Jerry的原创文章,尽在:“汪子熙”:
相关文章
- [Angular 9] Built-in template syntax $any
- [Angular] 'providedIn' for service
- [Angular] Difference between ViewChild and ContentChild
- [Angular 2] Import custom module
- [AngularJS] angular-md-table for Angular material design
- [AngularJS] Angular 1.3: ng-model-options updateOn, debounce
- [ngx-formly] Dynamically disable a Form field with Angular Formly
- [Angular] Control the dependency lookup with @Host, @Self, @SkipSelf and @Optional
- [Angular] Progress HTTP Events with 'HttpRequest'
- [Angular] Pluck value from Observable
- [Angular Directive] Write a Structural Directive in Angular 2
- [Angular] Isolate Scope .2
- [FE] 有效开展一个前端项目-V1 (gulp/angular)
- Angular 项目里使用 scss 文件的一些技巧分享
- Angular 如何为多个项目使用单一存储仓库
- Angular 项目 ng serve 背后发生的事情
- Angular 项目里的 tsconfig.json
- 什么是 Angular library 的 secondary entry points?
- Angular 项目中 angular.json builder 字段的可选项介绍
- Angular 项目中导入 styles 文件到 Component 中的一些技巧
- 在生产环境中调试 Angular 应用程序而不显示源映射
- 关于 Angular 项目里的 index.ts
- Angular 项目 tsconfig.json 里定义的 out-tsc 还有作用吗?
- Angular 项目里的 tsconfig.json
- Angular的property binding一个例子
- Angular component的一个例子
- Angular CLI创建的项目文件用途一栏