DEV Community

Cover image for How to simplify and organize imports in Typescript
Dany Paredes for This is Learning

Posted on • Updated on

How to simplify and organize imports in Typescript

Sometimes we have a long list of imports, with files that come from the same place, it makes our code noisy and a bit longer, something like:

import { BeersService } from './services/beers.service';
import { WhiskyService } from './services/whiski.service';
import { WineService } from './services/wine.service';
Enter fullscreen mode Exit fullscreen mode

We can simplify it by exposing all files, from a single file, to point to all of them.

Create drinks.ts into the service directory and export all services.

export * from './beers.service';
export * from './whiski.service';
export * from './wine.service';
Enter fullscreen mode Exit fullscreen mode

Now we can update our files, to the new path.

import { BeersService, WhiskyService, WineService } from './services/drinks';
Enter fullscreen mode Exit fullscreen mode

Thanks @lissetteibnz , If rename the filename from drinks.ts to index.ts, Javascript understand the file index like the entrypoint for the directory, so it works only using the directory name.

import { BeersService, WhiskyService, WineService } from './services';
Enter fullscreen mode Exit fullscreen mode

The code looks clean and easy to ready because all of them comes from the same place.

Photo by Marcin Jozwiak on Unsplash

Latest comments (5)

Collapse
 
flamesoff profile image
Artem

It could break project compilation in some cases.

Collapse
 
phnmtrung profile image
Phạm Thành Trung

Can bundler still do tree-shaking with import like this?

Collapse
 
layzee profile image
Lars Gyrup Brink Nielsen

Yes, that's how library entry points are structured.

Collapse
 
lissetteibnz profile image
Sara Lissette Luis Ibáñez

If you create a index.ts file with:
export * from './beers.service';
export * from './whiski.service';
export * from './wine.service';

After, you can import all services as:
import { BeersService, WhiskyService, WineService } from './services';

You don't need to add index

Collapse
 
danywalls profile image
Dany Paredes

Thanks! I update the post adding your buckets.

Seatle Storm