Typescript: Adding barrels into typescript
Let’s use barrel for more readable code
Ilearned recently called barrel that is simple but useful import/export strategy. If you are working on huge project, so you have to handle a bunch of imports statement, barrel might be a good solution for you.
So, what is barrels?
A barrel is a way to rollup exports from several modules into a single convenient module. The barrel itself is a module file that re-exports selected exports of other modules.
So when a barrel is useful? Let’s consider below scenario. Let’s say you are building a table component and it has three sub components. Then a folder structure is like below:
Table (folder)
- TableA.tsx
- TableB.tsx
- TableC.tsx
// Table/TableA.tsx
export TableA() {...}// Table/TableB.tsx
export TableB() {...}// Table/TableC.tsx
export TableC() {...}
If you need to import these three components, you are likely to import like this. It is normal but redundant, right?
import { TableA } from '../Table/TableA';
import { TableB } from '../Table/TableB';
import { TableC } from '../Table/TableC';
Adding barrels in typescript
Let’s refactor the code in cleaner and easier way using barrel. Barrel makes code more readable and maintainable.
First, create index.ts
inside Table folder. (Table/index.js
)
// Table/index.tsexport * from './TableA';
export * from './TableB';
export * from './TableC';
Once you re-export multiple modules, just import it at once. That’s it!
import { TableA, TableB, TableC } from '../Table';
Conclusion
Barrels is useful when your code is bigger and bigger. Barrel is not special features of typescript. You can also apply it in javascript.