【问题标题】:What are all the index.ts used for?所有 index.ts 的用途是什么?
【发布时间】:2016-09-30 14:23:48
【问题描述】:

我一直在查看一些种子项目,所有组件似乎都有一个 index.ts 可以从该组件导出 *。我在任何地方都找不到它的实际用途?

例如https://github.com/mgechev/angular2-seed/tree/master/src/client/app/%2Bhome

谢谢

【问题讨论】:

  • 与本次讨论相关的是github上的this issue。在将桶文件用于 Angular 项目之前,您可能需要通读它

标签: angular


【解决方案1】:

来自BarrelAngular.io v2's archived glossary条目*

桶是一种将多个模块的导出汇总为单个模块的方法 便利模块。桶本身是一个模块文件,可以重新导出 其他模块的选定导出。

想象一个英雄文件夹中的三个模块:

// 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

每个 Angular 作用域包都有一个名为 index 的桶。

另见EXCEPTION: Can't resolve all parameters


*注意:Barrel 已从 more recent versions of the Angular glossary 中删除。

更新 使用最新版本的 Angular,桶文件应编辑如下,

export { HeroModel } from './hero.model';  
export { HeroService } from './hero.service'; 
export { HeroComponent } from './hero.component';

【讨论】:

  • 当我执行相当于export * from './hero.model.ts' 的操作时,我会收到类似“'导入路径不能以'.ts''结尾”的消息,所以我只需更改为export * from './hero.model'。同样值得重复您对Angular not recommending barrels anymore的评论
  • @TheRedPea 感谢您的提示。我不想更改它,因为它是来自链接页面(早期版本)的引用
  • 你知道有没有帮助库或命令自动生成index.js?
  • @AlexanderAbakumov 由于组件、指令或管道必须属于一个且仅属于一个模块,因此通过在模块中声明上述任何内容,当您导入该模块时,您基本上可以实现相同的目标。 .. 假设您还从模块中导出了它们。
  • @Qwerty 我很确定这适用于 tree-shaking,但是很久以前建议的做法中删除了使用桶,我认为当模块在 1.0 之前引入时。
【解决方案2】:

index.ts 类似于 nodejs 中的 index.jsindex.html 是网站托管。

所以当你说import {} from 'directory_name' 时,它会在指定目录中查找index.ts 并导入那里导出的任何内容。

例如,如果您有calculator/index.ts

export function add() {...}
export function multiply() {...}

你可以的

import { add, multiply } from './calculator';

【讨论】:

  • @FlowerScape 在创建库或模块级代码时,通过索引导出特别有用,这样最终用户的导入就不那么冗长了。它还隐藏了导入代码的任何不必要/令人困惑的实现细节。
  • 重构。您可以更改代码,例如。重命名文件,只要保持 index.ts 中的导出相同。
【解决方案3】:

index.ts 帮助我们将所有相关的东西放在一起,我们不需要担心源文件名。

我们可以使用源文件夹名称导入所有东西。

import { getName, getAnyThing } from './util';

这里的 util 是文件夹名而不是文件名,它有 index.ts 重新导出所有四个文件。

export * from './util1';
export * from './util2';
export * from './util3';
export * from './util4';

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-10-08
    • 2011-12-21
    • 2012-06-03
    • 1970-01-01
    • 1970-01-01
    • 2010-09-27
    • 2011-12-17
    • 2010-11-21
    相关资源
    最近更新 更多