Barrel file is a single place to re export your functions, variables etc for your modules.
I have divided this post into
- Introduction
- Caveats
- Case Study
A ?️ or screenshot worth a thousand words.
As we can see above index.ts
export everything from nearby files. So now if I want to import a functionality from reducer.ts, I don’t need to specify path as
import { reducer } from 'store/reducer' // I can just write import {reducer} from 'store'
Because just like index.html file Module Loaders would look for index.ts by default.
It is a go to resource. It is a starting point of the journey.
In addition, the reducer.ts can reside another sub folder. We are still able to export its functionalities via index.ts
That’s what called Barrel files.
Barrel File Caveats
Although its is not directly related to barrel files i-e circular dependency. Circular dependency occurs when a Module A somehow imports itself.
Make sure you don’t get into this kind of trouble especially when using Barrel files.
Case Study: Helps in Renaming
I have personally experienced the need of renaming a file that was imported in barrel file. Just like above example I had to rename reducer to reducers.ts (plural form). Now without Barrel File architecture you need to reflect that name change in every file that use reducers.ts
Thanks to Barrel files, just rename the file in one place i-e index.ts and you are all set.