Angular Java Script Tutorials

Barrel file benefits in JavaScript

Barrel file is a single place to re export your functions, variables etc for your modules.

I have divided this post into

  1. Introduction
  2. Caveats
  3. Case Study

A 🖼️ or screenshot worth a thousand words.

index.ts example of barrel files in angular typescript technbuzz
index.ts depicted as Barrel File

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.

How circular dependency happens best explaned by
B imports A, C imports B
Things gets works when one Module somehow import itself
At the end of the day Module A 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.

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.