Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 661
jmbmage Avatar asked Jun 07 '16 14:06

jmbmage


People also ask

What is the purpose of index ts?

index. ts help us to keep all related thing together and we don't need to worry about the source file name. We can import all thing by using source folder name.

Should you use index ts files?

Generally you should create index. ts file in feature specific folders. But it is up to you how many index. ts file should be created, should it be feature specific, component specific etc.


1 Answers

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)

like image 169
Brocco Avatar answered Nov 03 '22 04:11

Brocco