Typescript: Adding barrels into typescript

Let’s use barrel for more readable code

Suyeon Kang
suyeonme
2 min readApr 24, 2021

--

Photo by Alex on Unsplash

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

If you need to import these three components, you are likely to import like this. It is normal but redundant, right?

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)

Once you re-export multiple modules, just import it at once. That’s it!

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.

--

--