Why does angular-cli create component/shared/index.ts?

那年仲夏 提交于 2019-12-08 15:33:43

问题


If I run this:

ng g component components/blogs

I get

app
+--components
| +--blogs
| |  +--shared
| |  |  +--index.ts              // what's this for?
| |  +--blogs.component.css
| |  +--blogs.component.html
| |  +--blogs.component.ts
| |  +--blogs.component.spec.ts  // unit tests!
| |  +--index.ts

I understand the rest, but what is the /blogs/shared/index.ts for? Why does a component have a shared folder if that component folder is just for the component?


回答1:


The idea of the index.ts file in the shared dir is something called a barrel.

The goal of the barrel it to consolidate imports. It will export the items contained within shared to make the imports in blogs.component.ts cleaner...

app/components/blogs/shared/blogs.service.ts

export class BlogsService { ... }

app/components/blogs/shared/blog.model.ts

export class Blog { ... }

app/components/blogs/shared/index.ts

export * from './blogs.service';
export * from './blog.model';

app/components/blogs/blogs.component.ts

// without barrel
import { BlogsSerivce } from './shared/blogs.service';
import { Blog } from './shared/blog.model';

// with barrel
import { BlogService, Blog } from './shared';

And if you can imagine this becomes much more consolidated as you add more components/services/directives/models.

REFERENCE You can read about barrels in the official style guide (Thanks to Günter Zöchbauer)



来源:https://stackoverflow.com/questions/37682372/why-does-angular-cli-create-component-shared-index-ts

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!